Java HttpURLConnection
1 什么是Java HttpURLConnection
Java HttpURLConnection类是http特定的URLConnection。它仅适用于HTTP协议。
借助于HttpURLConnection类,您可以获取任何HTTP URL的信息,例如请求头信息,状态代码,响应代码等。
java.net.HttpURLConnection是URLConnection类的子类。
2 如何获取HttpURLConnection对象
public URLConnection openConnection()throws IOException{}
您可以将其转换为HttpURLConnection类型,如下:
URL url=new URL("http://www.yiidian.com/java");
HttpURLConnection huc=(HttpURLConnection)url.openConnection();
3 Java HttpURLConnection的例子
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java HttpURLConnection的例子
*/
import java.io.*;
import java.net.*;
public class Demo{
public static void main(String[] args){
try{
URL url=new URL("http://www.yiidian.com/java");
HttpURLConnection huc=(HttpURLConnection)url.openConnection();
for(int i=1;i<=8;i++){
System.out.println(huc.getHeaderFieldKey(i)+" = "+huc.getHeaderField(i));
}
huc.disconnect();
}catch(Exception e){System.out.println(e);}
}
}
输出结果为:
Date = Mon, 27 Apr 2020 01:12:48 GMT
Server = Apache/2.4.7 (Ubuntu)
Last-Modified = Sun, 26 Apr 2020 03:43:18 GMT
ETag = "6f10-5a429663126bf"
Accept-Ranges = bytes
Content-Length = 28432
Vary = Accept-Encoding
Keep-Alive = timeout=5, max=100
热门文章
优秀文章