新套接字被斜线搞砸了?

时间:2016-10-14 06:19:32

标签: java sockets slash

我有一个试图通过套接字发出HTTP请求的java程序。由于某种原因,字符串中的斜线会弄乱它。

我有一个try / catch,一旦使用带有斜杠的字符串创建套接字就会被捕获。

%d

响应

        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);

我正在尝试访问具有斜杠的主机名和路径的特定站点。发生了什么事?

2 个答案:

答案 0 :(得分:1)

由于错误的请求路径而发生第一个错误HTTP/1.1 400 Bad Request。在不知道你的代码的情况下很难找到原因。

第二个错误就像Andy Turner已经说过的那样,因为主机名错了。 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");

答案 1 :(得分:0)

IOException更具体,你得到一个UnknownHostExceptionIOException的子类),因为主机名不能包含斜杠。

您应该在catch块中打印/记录异常的堆栈跟踪;这个问题会更加明显。

相关问题