HTTP 客户端错误请求 400

标签 http netbeans get httpclient bad-request

我正在尝试了解 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/

相关文章:

delphi - 如果我正在处理的请求已被取消,如何通知我?

php - NetBeans PHP - 重构

Java Jersey 使用 GET 返回 JSON,仅返回部分字段而不是全部

PHP "INSERT INTO"不工作

java - 无法在 WildFly 10 中上传超过 1MB 的文件?

php - 使用 PHP/JavaScript 从服务器向用户推送通知

ios - 使用 Moya 获取响应头

java - Netbeans 中可以播放声音,但 jar 中不能播放声音

java - 如何从 Netbeans IDE 中的现有类生成类图

java - 如何从HTTP请求中获取正确的数据