URL
url(统一资源定位符),通过URL可以从互联网中找到位于Http服务器中的相关资源.
URL构成
http协议://主机地址:端口号/资源地址?查询信息
http://www.softeem.com:80/index?name=XXX&pwd=XXX
一些关于URL的方法:
public class UrlDemo {
public static void main(String[] args) throws Exception {
String path = "http://hk.softeem.top:80/blog/main.jsp?name=admin";
//根据字符串的url地址构建一个URL对象
URL url = new URL(path);
//获取协议部分
String protocol = url.getProtocol();
System.out.println(protocol);
//获取主机地址
String host = url.getHost();
System.out.println(host);
//获取端口
int port = url.getPort();
System.out.println(port);
//获取请求资源
String path1 = url.getPath();
System.out.println(path1);
//获取查询地址(?后面就是查询)
String query = url.getQuery();
System.out.println(query);
//URLConnection是个抽象类
//打开一个URL连接并且获取一个连接对象
HttpURLConnection coon = (HttpURLConnection) url.openConnection();
//设置请求方式
coon.setRequestMethod("GET");
//获取请求的数据长度(字节)
int len = coon.getContentLength();
System.out.println(len);
//
String enc = coon.getContentEncoding();
System.out.println(enc);
//coon.connect();
//获取响应状态码(看是否运行成功)
int code = coon.getResponseCode();
if(code == HttpURLConnection.HTTP_OK){
InputStream is = coon.getInputStream();
//字节输入流转换成字符输入流
InputStreamReader isr = new InputStreamReader(is,"utf-8");//这里的utf-8字符编码.
//缓冲流
BufferedReader br = new BufferedReader(isr);
//因为的文本是一行,因此想到用bufferedRead
String data = br.readLine();
System.out.println(data);
}
}
}