使用Java套接字获取GET请求 [英] GET request with Java sockets
问题描述
我正在编写一个简单的程序来向特定网址发送get请求 http://badunetworks.com/about / 。如果我将其发送到 http://badunetworks.com ,请求仍然有效,但我需要将其发送到关于页面。
I am writing a simple program to send a get request to a specific url "http://badunetworks.com/about/". The request works if I send it to "http://badunetworks.com" but I need to send it to the about page.
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();
}
}
推荐答案
如果about页面链接是about.html,那么你已将此行wtr.println(GET / HTTP / 1.1)更改为wtr.println(GET /about.html HTTP / 1.1) )。
if the about page link is about.html ,then you have change this line wtr.println("GET / HTTP/1.1") into wtr.println("GET /about.html HTTP/1.1").
在套接字创建中删除/ about
in socket creation remove the /about
wtr.println(GET / HTTP / 1.1 ); --->此行调用您指定的主机的主页。
wtr.println("GET / HTTP/1.1");--->this line call the home page of the host you specified.
这篇关于使用Java套接字获取GET请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!