使用Socket进行网络编程,从网络传输层角度进行分析,适用于绝大多数网络连接方式;但是需要开发人员熟练掌握网络传输、网络协议等基础知识,开发难度较大。在Java语言中,提供了一组URL处理类,封装了Socket编程技术的实现细节,用来方便开发人员进行网络连接、网络数据传输等常用的网络任务。
直接使用URL类,可以方便地处理各种常见协议的网络连接 使用URL类进行网络连接,相当于直接进行远程输入/输出流操作,只需开发人员熟练掌握常用IO操作即可,大大降低开发难度。
URL类:可以获取网页的各种信息
URL myURL = new URL("http://java.sun.com");
String protocal = myURL.getProtocol();
String host = myURL.getHost();
String file = myURL.getFile();
int port = myURL.getPort();
String ref = myURL.getRef();
System.out.println(protocal + ", " + host + ", " + file + ", " + port + ", " + ref);
URLconnection类:可以建立与URL的连接,读取或写入URL引用的资源
// URLConnection类常用方法
// 获得响应消息头类方法
getContentType()
getContentLength()
getContentEncoding()
// 获得响应消息主体
getContent()
// 获得当前连接输入/输出流对象
getInputStream()
getOutputStream()
文件下载
url = new URL("http://");
// 打开连接
URLConnection conn = url.openConnection();
// 得到输入流
InputStream is = conn.getInputStream();
// 关于IO流的用法和写法一定要熟悉
OutputStream os = new FileOutputStream("d:\\baidu.png");
byte[] buffer = new byte[2048];
int length = 0;
while (-1 != (length = is.read(buffer, 0, buffer.length))) {
os.write(buffer, 0, length);
}
is.close();
os.close();
获取响应消息
// 创建Url对象
URL url = new URL(rootUrl);
// 得到URLConnection连接对象
URLConnection conn = url.openConnection();
HttpURLConnection hc = (HttpURLConnection)conn;
// 获得响应消息头
conn.getContentType();
conn.getContentLength();
conn.getContentEncoding();
// 获得HTTP消息状态码
hc.getResponseCode();
hc.getResponseMessage();
// 获得HTTP响应消息主体
hc.getContent();