2

我正在尝试了解 HTTP 客户端如何在 Java 中工作。我正在尝试构建自己的客户端,该客户端将向 Web 服务器请求 php 文件。

目前,当我发出请求时,服务器会给我以下错误:

HTTP/1.1 400 错误请求

但是,我可以从浏览器中访问该文件没问题。我不知道我可能做错了什么,但我无法弄清楚。下面是我的 HTTP 客户端类的代码:

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
4

2 回答 2

3

不要使用 PrintWriter。你必须写 ascii 字符。

 s.getOutputStream().write(("GET " + path + " HTTP/1.1\r\n\r\n").getBytes("ASCII"));
于 2013-01-29T00:14:59.573 回答
1

我认为您至少需要在Host请求中添加标头。

示例取自http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol

GET /index.html HTTP/1.1
Host: www.example.com

标头完成后,您还需要传输额外\r\n的,以便服务器知道请求已完成。

不要使用println但是printprintln为每一行添加另一个\n,导致行以 . 结尾\r\n\n

于 2013-01-28T23:43:46.310 回答