java - 新 socket 被斜杠弄乱了?

标签 java sockets slash

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

相关文章:

java - 如何在同一屏幕上拥有按钮和自定义绘画 View ?安卓

java - 空指针异常Hadoop

java - 为什么 substring() 函数应该返回溢出消息却返回值

java - 服务器端 客户端 JAVA 游戏 Action

python - '/' or '\' 路径?

go - 当我的通配符参数中有双斜杠时,为什么 Gorilla mux 会重定向?

java - 创建 Java 翻转多米诺骨牌游戏

ios - iOS 设备上的 rabbitmq-c 不工作

javascript - 在 Node Js 上运行服务器时未定义套接字

php - 带斜杠的 ZF2 路由参数