java-在通过TCP套接字发送手工制作的HTTP请求时,为什么会收到HTTP 400错误请求响应?

我正在尝试手动建立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 = "https://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>

为什么呢

最佳答案

感谢Julian Reschke的建议,我错过了两个空格字符(一个在HTTP动词之后,一个在路径之后)

 

 

String request = "GET " + path + " HTTP/1.1\n";
//                   ^            ^
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值