我正在尝试了解HTTP客户端如何在Java中工作。我正在尝试构建自己的客户端,该客户端将向Web服务器请求php文件。
目前,当我发出请求时,服务器会给我以下错误:
HTTP / 1.1 400错误请求
但是,我能够在浏览器中访问该文件没问题。我不知道我做错了什么,但我无法理解。下面是我的HTTP Client类的代码:
public class MyHttpClient {
MyHttpRequest request;
String host;
public MyHttpResponse execute(MyHttpRequest request) throws IOException {
//Creating the response object
MyHttpResponse response = new MyHttpResponse();
//Get web server host and port from request.
String host = request.getHost();
int port = request.getPort();
//Check 1: HOST AND PORT NAME CORRECT!
System.out.println("host: " + host + " port: " + String.valueOf(port));
//Get resource path on web server from requests.
String path = request.getPath();
//Check 2: ENSURE PATH IS CORRECT!
System.out.println("path: " + path);
//Open connection to the web server
Socket s = new Socket(host, port);
//Get Socket input stream and wrap it in Buffered Reader so it can be read line by line.
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
//Get Socket output stream and wrap it in a Buffered Writer so it can be written to line by line.
PrintWriter outToServer = new PrintWriter(s.getOutputStream(),true);
//Get request method
String method = request.getMethod();
//Check 3: ENSURE REQUEST IS CORRECT GET/POST!
System.out.println("Method: " + method);
//GET REQUEST
if(method.equalsIgnoreCase("GET")){
//Send request to server
outToServer.println("GET " + path + " HTTP/1.1 " + "\r\n");
String line = inFromServer.readLine();
System.out.println("Line: " + line);
}
//Returning the response
return response;
}
}
如果有人能对这个问题有所了解,我会非常感激!感谢。
对服务器的新请求:
outToServer.print("GET " + path+ " HTTP/1.1" + "\r\n");
outToServer.print("Host: " + host + "\r\n");
outToServer.print("\r\n");
响应:
方法:GET
line: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
line: <html><head>
line: <title>400 Bad Request</title>
line: </head><body>
line: <h1>Bad Request</h1>
line: <p>Your browser sent a request that this server could not understand.<br />
line: </p>
line: <hr>
line: <address>Apache Server at default.secureserver.net Port 80</address>
line: </body></html>
line: null
答案 0 :(得分:2)
不要使用PrintWriter。你必须写ascii字符。
s.getOutputStream().write(("GET " + path + " HTTP/1.1\r\n\r\n").getBytes("ASCII"));
答案 1 :(得分:1)
我认为您至少需要在请求中添加Host
标头。
取自http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol
的示例GET /index.html HTTP/1.1
Host: www.example.com
标题完成后,您还需要传输额外的\r\n
,以便服务器知道请求已完成。
请勿使用println
,print
。 println
为每一行添加了另一个\n
,导致这些行以\r\n\n
终止。