为什么在通过TCP套接字发送手动制作的HTTP请求时,我收到HTTP 400错误的请求响应? [英] Why am I getting a HTTP 400 bad request response when sending a manually-crafted HTTP request over a TCP socket?
本文介绍了为什么在通过TCP套接字发送手动制作的HTTP请求时,我收到HTTP 400错误的请求响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试手动构建HTTP请求(作为字符串)并通过TCP套接字发送,这就是我要做的事情:
I'm trying to build an HTTP request manually (as a string) and send it over a TCP socket, this is what I'm trying to do:
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:
But I'm getting this response message whatever the URL is chosen:
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动词和路径后面的第二个)
Thanks to Julian Reschke for the suggestion , I was missing tow space characters (One after the HTTP verb and the second after the path)
String request = "GET " + path + " HTTP/1.1\n";
// ^ ^
这篇关于为什么在通过TCP套接字发送手动制作的HTTP请求时,我收到HTTP 400错误的请求响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文