package com.neutron.network.url;
import java.net.MalformedURLException;
import java.net.URL;
/**
* URL案例
* @author zhanght
*
*/
public class URLDemo {
/**
* 主要查看URL的作用
*/
public static void checkURL() throws MalformedURLException{
URL url = new URL("https://www.baidu.com/index.php?tn=site5566");
String protocol = url.getProtocol(); // 协议
String host = url.getHost(); // 主机名
int port = url.getPort(); // 端口名
String file = url.getFile(); // 文件名称
String path = url.getPath(); // 资源路径
String query = url.getQuery(); // 查询参数
StringBuffer buffer = new StringBuffer("");
buffer.append("protocol:" + protocol + "\n")
.append("host:" + host + "\n")
.append("port:" + port + "\n")
.append("file:" + file + "\n")
.append("path: " + path + "\n")
.append("query: "+ query);
System.out.println(buffer.toString());
}
public static void main(String[] args) throws MalformedURLException {
checkURL();
}
}
package com.neutron.network.url;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
/**
* URLConnection案例
* @author zhanght
*
*/
public class URLConnectionDemo {
public static void main(String[] args) throws IOException {
URL url = new URL("https://www.baidu.com/index.php?tn=site5566");
// 获取url所引用的远程对象的连接,相当于获取socket操作
URLConnection conn = url.openConnection();
System.out.println("conn: " + conn);
// 相当于获取socket中输入流操作
InputStream in = conn.getInputStream();
// 存储返回的数据
byte[] buff = new byte[1024];
// 读取返回的数据
int len = in.read(buff);
System.out.println(new String(buff, 0, len));
/*
* URLConnection是应用层api,已经将从传输层传递过来的数据做进一步拆包操作,因此我们没有看到传递过来的数据有数据返回头信息
*/
}
// conn: sun.net.www.protocol.https.DelegateHttpsURLConnection:https://www.baidu.com/index.php?tn=site5566
// <html>
// <head>
// <script>
// location.replace(location.href.replace("https://","http://"));
// </script>
// </head>
// <body>
// <noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>
// </body>
// </html>
}
注意:URL和URLConnection是应用层API,已经将传输层数据做拆包处理。