2012-02-23 136 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()