📜  Java HttpURLConnection类

📅  最后修改于: 2020-09-28 03:11:25             🧑  作者: Mango

Java HttpURLConnection类

Java HttpURLConnection类是http特定的URLConnection。它仅适用于HTTP协议。

借助于HttpURLConnection类,您可以获取任何HTTP URL的信息,例如标头信息,状态代码,响应代码等。

java.net.HttpURLConnection是URLConnection类的子类。

如何获取HttpURLConnection类的对象

URL类的openConnection()方法返回URLConnection类的对象。句法:

public URLConnection openConnection()throws IOException{}

您可以将其转换为HttpURLConnection类型,如下所示。

URL url=new URL("http://www.javatpoint.com/java-tutorial");  
HttpURLConnection huc=(HttpURLConnection)url.openConnection();

Java HttpURLConnecton示例

import java.io.*;  
import java.net.*;  
public class HttpURLConnectionDemo{  
public static void main(String[] args){  
try{  
URL url=new URL("http://www.javatpoint.com/java-tutorial");  
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 = Wed, 10 Dec 2014 19:31:14 GMT
Set-Cookie = JSESSIONID=D70B87DBB832820CACA5998C90939D48; Path=/
Content-Type = text/html
Cache-Control = max-age=2592000
Expires = Fri, 09 Jan 2015 19:31:14 GMT
Vary = Accept-Encoding,User-Agent
Connection = close
Transfer-Encoding = chunked