我正在尝试了解 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");
回应:
方法:获取
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
最佳答案
不要使用PrintWriter。您必须编写 ascii 字符。
s.getOutputStream().write(("GET " + path + " HTTP/1.1\r\n\r\n").getBytes("ASCII"));
关于HTTP 客户端错误请求 400,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14573264/