我有一个 java 程序,它试图通过套接字发出 HTTP 请求。由于某种原因,字符串中的斜杠弄乱了它。
我有一个 try/catch,一旦使用带有斜杠的字符串创建套接字,它就会被捕获。
Socket socket = new Socket("www.google.ca", port);
回应
HTTP/1.1 400 Bad Request
Content-Length: 54
Content-Type: text/html; charset=UTF-8
Date: Fri, 14 Oct 2016 06:05:43 GMT
Connection: close
<html><title>Error 400 (Bad Request)!!1</title></html>
现在加一个斜线
Socket socket = new Socket("www.google.ca/", port);
被捕获了。
我的要求。
outputStream.println("GET / HTTP/1.1");
outputStream.println("");
outputStream.flush();
我正在尝试使用带有斜杠的主机名和路径访问特定站点。发生了什么事?
最佳答案
第一个错误HTTP/1.1 400 Bad Request
是由于请求路径错误而发生的。如果不知道你的代码,很难找到原因。
第二个错误的发生就像安迪·特纳已经说过的那样,因为主机名错误。 InetAddress无法解析带有斜杠的主机名。
这个例子对我有用:
public static void main(String[] args) throws Exception {
Socket s = new Socket(InetAddress.getByName("google.com"), 80);
PrintWriter pw = new PrintWriter(s.getOutputStream());
pw.println("GET /about/ HTTP/1.1"); // here comes the path
pw.println("f-Modified-Since: Wed, 1 Oct 2017 07:00:00 GMT");
pw.println("");
pw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line;
while((line = br.readLine()) != null){
System.out.println(line);
}
br.close();
}
您只需在这一行中设置路径:
pw.println("GET /about HTTP/1.1");
关于java - 新 socket 被斜杠弄乱了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40036242/