2012-02-23 93 views
0

我有這個代碼閱讀網頁。由於身份驗證,我需要發送http頭到服務器。我應該怎麼做?我需要使用套接字嗎?因爲這是我迄今爲止發現的。發送Http頭標識

URL url = new URL("http://www.page.com/"); 

URLConnection yc = url.openConnection(); 
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream())); 

String inputLine; 

while ((inputLine = in.readLine()) != null) 
     System.out.println(inputLine); 
in.close(); 

我發現這個代碼用於發送http請求頭。

Socket sock = new Socket(url.getHost(), port); 
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(sock.getOutputStream())); 
out.writeBytes("GET " + url.getFile() + " HTTP/1.0\n"); 
out.writeBytes("User-Agent: " + user_agent + "\n"); 
out.writeBytes("From: " + email_address + "\n"); 
out.writeBytes("Host: " + url.getHost() + "\n"); 
out.writeBytes("\n"); 
out.flush(); 

我不知道如果我能以某種方式結合這兩個代碼,或者我需要改變閱讀頁面的方式,能夠發送頭。

謝謝!

+1

參見:http://stackoverflow.com/questions/1144073 – TacticalCoder 2012-02-23 01:05:13

回答

0

目前尚不清楚「因爲鑑定」什麼意思,但如果你知道你需要什麼頭字段,你可以將它們添加:

URLConnection conn = new URLConnection(url); 
conn.addRequestProperty("myHeaderField", "myHeaderValue"); 
conn.openConnection()