gpt4 book ai didi

java - 新 socket 被斜杠弄乱了?

转载 作者:行者123 更新时间:2023-11-30 07:06:32 24 4
gpt4 key购买 nike

我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com