【问题标题】:Bad request error when reading a web page读取网页时出现错误的请求错误
【发布时间】:2012-10-18 05:39:15
【问题描述】:

我试图以字节为单位读取网页,但它总是在我的 java 控制台上返回“Bad Request Error 400”消息(我在控制台上显示内容)。我找不到纠正它的方法,可能是因为我阅读了字节码。这是我的代码和结果:

Socket s = new Socket(InetAddress.getByName(req.hostname), 80);
                    PrintWriter socketOut = new PrintWriter(s.getOutputStream());
                    socketOut.print("GET "+ req.url + "\n\n");
                    socketOut.flush();
                    BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

                    StringBuffer buffer = new StringBuffer();
                    int data = in.read();
                    while (data != -1) {
                      char theChar = (char) data;
                      buffer.append(theChar);
                      data = in.read();
                    }
                    in.close();
                    byte[] result = buffer.toString().getBytes();
                    out.write(result);

结果包含从错误请求消息开始的 html 标签,但我删除了它们,所以这是我的结果:

Thread with id 10 URL: http://www.facebook.com.tr/
Host: www.facebook.com.tr
HTTP/1.1 400 Bad Request
Content-Type: text/html
Date: Wed, 17 Oct 2012 10:18:06 GMT
Connection: close
Content-Length: 134

400 Bad Request
Method Not Implemented
Invalid method in request

【问题讨论】:

    标签: java


    【解决方案1】:

    当您向 HTTP 服务器发送不正确或不适当的请求时,将向 HTTP 服务发送错误代码 400。你必须确定你的要求是否正确。我看到www.facebook.com.tr。检查.tr

    【讨论】:

      【解决方案2】:

      我想这是因为您的代码无法处理它在初始握手中收到的永久重定向:

      $>> curl --head www.facebook.com.tr/
      HTTP/1.1 301 Moved Permanently
      Location: http://www.facebook.com/
      Content-Type: text/html; charset=utf-8
      X-FB-Debug: WOU3E4EGqo5Rxch8AnUzqcWg9CcM1p55pt1P9Wrm0QI=
      Date: Wed, 17 Oct 2012 10:33:12 GMT
      Connection: keep-alive
      Content-Length: 0
      

      还要检查您的问题,您收到的是 400 而不是 404。

      试试这个:

      BufferedReader reader = new BufferedReader(new InputStreamReader(new URL("http://www.facebook.com.tr").openStream()));
      
      String line = reader.readLine();
      while(line!=null) {
          System.out.println(line);
          line = reader.readLine();
      }
      

      【讨论】:

      • 网址不仅仅是一个文本文件,您正在尝试与网络服务器通信,并且需要执行某些握手来获取您想要的信息。我会用一些应该做你想做的代码来更新我的答案。
      【解决方案3】:

      服务器不容忍没有 HTTP-Version 声明的 HTTP 请求。试试这样:

      socketOut.print("GET "+ req.url + " HTTP/1.1\n\n");
      

      还要考虑到服务器保持连接处于活动状态,所以在某些时候data = in.read() 会锁定主线程。除非您终止连接或执行其他操作,否则您的循环将需要一段时间才能结束,直到连接超时。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-13
        • 1970-01-01
        • 2018-04-02
        • 1970-01-01
        相关资源
        最近更新 更多