use*_*794 5 java sockets get http
我正在编写一个简单的程序,将获取请求发送到特定的URL“ http://badunetworks.com/about/ ”。如果我将请求发送到“ http://badunetworks.com ”,则该请求有效,但我需要将其发送到“关于”页面。
package badunetworks;
import java.io.*;
import java.net.*;
public class GetRequest {
public static void main(String[] args) throws Exception {
GetRequest getReq = new GetRequest();
//Runs SendReq passing in the url and port from the command line
getReq.SendReq("www.badunetworks.com/about/", 80);
}
public void SendReq(String url, int port) throws Exception {
//Instantiate a new socket
Socket s = new Socket("www.badunetworks.com/about/", port);
//Instantiates a new PrintWriter passing in the sockets output stream
PrintWriter wtr = new PrintWriter(s.getOutputStream());
//Prints the request string to the output stream
wtr.println("GET / HTTP/1.1");
wtr.println("Host: www.badunetworks.com");
wtr.println("");
wtr.flush();
//Creates a BufferedReader that contains the server response
BufferedReader bufRead = new BufferedReader(new InputStreamReader(s.getInputStream()));
String outStr;
//Prints each line of the response
while((outStr = bufRead.readLine()) != null){
System.out.println(outStr);
}
//Closes out buffer and writer
bufRead.close();
wtr.close();
}
}
Run Code Online (Sandbox Code Playgroud)
如果关于页面链接是 about.html ,那么您已将此行更改wtr.println("GET / HTTP/1.1")
为wtr.println("GET /about.html HTTP/1.1").
在套接字创建中删除 /about
wtr.println("GET / HTTP/1.1");
--->此行调用您指定的主机的主页。