在利用Java網路程式設計時,常常需要獲取HTTP請求頭,那麼JAVA如何獲取HTTP請求頭呢?下面小編為大家介紹了JAVA獲取HTTP請求頭的.方法,希望能幫到大家!
在利用Java網路程式設計時,利用Java獲取HTTP Request 和 Response頭欄位,可以利用Java語言根據需要新增自定義的HTTP頭欄位,而不必拘泥於標準HTTP定義的頭欄位。
程式碼如下:
public class TestURL {
public static void main(String[] args) {
String destURLStr= "";
URL destURL = null;
URLConnection urlCon = null;
HttpURLConnection httpUrlCon= null;
String readResFile = "C:/Users/zhoujw/Desktop/";
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(readResFile));
destURL = new URL(destURLStr);
urlCon = Connection();
httpUrlCon = (HttpURLConnection)urlCon;
//set request property
equestProperty("Accept-Encoding", "gzip,deflate,sdch");
//可根據需要新增自定義請求頭
equestProperty("Test Header1", "test1");
equestProperty("Test Header2", "test2");
ect();
BufferedReader br = new BufferedReader(new InputStreamReader(nputStream(), "gbk"));
String webpage = null;
while((( webpage = Line()) != null))
{
// tln(webpage);
e(webpage);
h();
}
//debug
tln("Self Define Headers:");
tln(" Test Header1: " + equestProperty("Test Header1"));
tln(" Test Header2: " + equestProperty("Test Header2"));
tln();
//echo request property
echoRequestHeaders(httpUrlCon);
//echo response property
echoResponseHeaders(httpUrlCon);
} catch (MalformedURLException e) {
tStackTrace();
} catch (IOException e) {
tStackTrace();
}
}
public static void echoRequestHeaders(HttpURLConnection httpUrlCon){
tln("Request Headers:");
tln(" " + equestMethod() + " / " + " HTTP/1.1");
tln(" Host: " + equestProperty("Host"));
tln(" Connection: " + equestProperty("Connection"));
tln(" Accept: " + equestProperty("Accept"));
tln(" User-Agent: " + equestProperty("User-Agent"));
tln(" Accept-Encoding: " + equestProperty("Accept-Encoding"));
tln(" Accept-Language: " + equestProperty("Accept-Language"));
tln(" Cookie: " + equestProperty("Cookie"));
tln(" Connection: " + eaderField("Connection"));//利用另一種讀取HTTP頭欄位
tln();
}
public static void echoResponseHeaders(HttpURLConnection httpUrlCon) throws IOException{
tln("Response Headers:");
tln(" " + "HTTP/1.1 " + esponseCode() + " " + esponseMessage());
tln(" status: " + esponseCode() + " " + esponseMessage());
tln(" content-encoding: " + ontentEncoding());
tln(" content-length : " + ontentLength());
tln(" content-type: " + ontentType());
tln(" Date: " + ate());
tln(" ConnectTimeout: " + onnectTimeout());
tln(" expires: " + xpiration());
tln(" content-type: " + eaderField("content-type"));//利用另一種讀取HTTP頭欄位
tln();
}
}
執行結果:
Self Define Headers:
Test Header1: test1
Test Header2: test2
Request Headers:
GET / HTTP/1.1
Host:
Connection: keep-alive
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
User-Agent: Java/1.6.0_20
Accept-Encoding: gzip,deflate,sdch
Accept-Language: null
Cookie: null
Connection: Keep-Alive
Response Headers:
HTTP/1.1 200 OK
status: 200 OK
content-encoding: gzip
content-length : -1
content-type: text/html; charset=utf-8
Date: 1427817028000
ConnectTimeout: 0
expires: 1427817001000
content-type: text/html; charset=utf-8