当我通过TCP套接字发送手动创建的HTTP请求时,为什么会收到HTTP 400错误响应?

3
我正在尝试手动构建一个HTTP请求字符串并通过TCP套接字发送它,这就是我要做的事情:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * SimpleHttpClient.java (UTF-8)
 *
 * Mar 27, 2014
 *
 * @author tarrsalah.org
 */
public class SimpleHttpClient {
    private static final String StackOverflow = "http://stackoverflow.com/";

    public static void main(String[] args) {

//      if (args.length < 1) {
//          System.out.println("Usage : SimpleHttpClient <url>");
//          return;
//      }

        try {
            URL url = new URL(StackOverflow);
            String host = url.getHost();
            String path = url.getPath();
            int port = url.getPort();
            if (port < 80) {
                port = 80;
            }

            //Construct and send the HTTP request
            String request = "GET" + path + "HTTP/1.1\n";
            request += "host: " + host;
            request += "\n\n";

            // Open a TCP connection
            Socket socket  = new Socket(host, port);
            // Send the request over the socket
            PrintWriter writer = new PrintWriter(socket.getOutputStream());
            writer.print(request);
            writer.flush();
            // Read the response
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String next_record = null;
            while ((next_record = reader.readLine()) != null) {
                System.out.println(next_record);
            }
            socket.close();
        } catch (MalformedURLException ex) {
            Logger.getLogger(SimpleHttpClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(SimpleHttpClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

但无论选择哪个URL,我都会收到这个响应消息:
HTTP/1.0 400 Bad request
Cache-Control: no-cache
Connection: close
Content-Type: text/html

<html><body><h1>400 Bad request</h1>
Your browser sent an invalid request.
</body></html>

为什么?

可能是重复的问题:通过套接字手动发送HTTP请求 - Jeroen
1
检查一下你发送的内容怎么样?HTTP跟踪?写入System.out? - Julian Reschke
2个回答

3
感谢朱利安 · 雷施克的建议,我漏掉了两个空格(一个在HTTP动词后面,另一个在路径后面)。
String request = "GET " + path + " HTTP/1.1\n";
//                   ^            ^

0

我其实有点不确定这个是否解决了你的问题,但是如果你阅读RFC2616, section 5,你会注意到它非常明确地提到在Request-line和头部之后需要有CRLF,所以你的代码中可能缺少一些\r

祝好,


这会引起一个400吗? - Sotirios Delimanolis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接