我有这个代码用于阅读网页。由于识别,我需要将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();
我不知道我是否能以某种方式合并这两个代码,或者我需要改变阅读页面的方式才能发送标题。
谢谢!
答案 0 :(得分:0)
目前尚不清楚'因为识别'的含义,但如果您知道需要哪些标题字段,可以添加它们:
URLConnection conn = new URLConnection(url);
conn.addRequestProperty("myHeaderField", "myHeaderValue");
conn.openConnection()