【问题标题】:connection to the URL fails but when I directly try in the browser, it succeeds连接到 URL 失败,但是当我直接在浏览器中尝试时,它会成功
【发布时间】:2012-12-19 00:30:47
【问题描述】:

下面的 sn-p 尝试将 2 个参数连同一个 URL 发送到一个 servlet。但是当我尝试这个 sn-p 时,我收到一条消息:

Connection to file server failed

但如果我直接尝试网址:

http://localhost:8084/nappster/ReceiveFileName?fileName=" + fileName + "&ip=" + IP

有了数据,没有问题。 Servlet 接收文件名并按预期处理它。当我尝试通过代码连接到 URL 时,可能是什么原因导致在浏览器中尝试连接失败并成功。

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String fileName = request.getParameter("FileTag");
    String IP = new ClientAddress().getNetworkIP();                
    // Send the file name to the nappster server 
    URL url = new URL("http://localhost:8084/nappster/ReceiveFileName?fileName=" + fileName + "&ip=" + IP);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    if(connection.getResponseCode() == 200) {
        // File name sent successfully to the server
        System.out.println("Connection to file server successful");
        System.out.println("--------");
    } else {
        // Unable to send file name to the server
        System.out.println("Connection to file server failed");

     }
}

注意:

我尝试上述 sn-p 时返回的响应码是 505

【问题讨论】:

  • 浏览器中可能存在您没有注意到的重定向 - 尝试打印更多数据,而不仅仅是 System.out.println("Connection to file server failed");
  • 返回的responseCode 是什么?
  • 收到响应码后能否打印connection.getResponseCode()的值?
  • 不支持 HTTP 版本...我认为 HttpUrlConnection 只是 v1.0,您可能想尝试类似 HttpComponents (hc.apache.org) 的东西 - 服务器可能需要 1.1。
  • @cjstehno 但是当我在另一个 servlet 中尝试时它工作正常。例如http://localhost:8084/nappster/ReceiveInformation?" + information

标签: java servlets httpconnection


【解决方案1】:

尝试使用url.encode() 方法。

【讨论】:

  • 您传递的信息可能包含字母字符、数字和一些在 URL 字符串中有意义的特殊字符。所以为了避免我们使用编码。请检查您的文件名或ip参数是否有这些。
  • 但是我可以直接在浏览器中访问 URL。怎么样?
  • 浏览器在发布到服务器之前默认对 url 进行编码。
  • 请分享您现在得到的实际 URL 和响应码
  • 参见stackoverflow.com/questions/10786042/java-url-encoding 了解如何使用 URLEncoder 正确编码 URL 的示例
猜你喜欢
  • 1970-01-01
  • 2014-04-25
  • 2020-01-07
  • 1970-01-01
  • 2012-02-21
  • 1970-01-01
  • 2018-07-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多