Java HttpURLConnection类

本文概述

  • 如何获取HttpURLConnection类的对象
  • Java HttpURLConnecton示例
Java HttpURLConnection类是http特定的URLConnection。它仅适用于HTTP协议。
借助于HttpURLConnection类, 你可以获取任何HTTP URL的信息, 例如标头信息, 状态代码, 响应代码等。
【Java HttpURLConnection类】java.net.HttpURLConnection是URLConnection类的子类。
如何获取HttpURLConnection类的对象URL类的openConnection()方法返回URLConnection类的对象。句法:
public URLConnection openConnection()throws IOException{}

你可以将其转换为HttpURLConnection类型, 如下所示。
URL url=new URL("http://www.srcmini.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.srcmini.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

    推荐阅读