与URL的连接失败,但是当我直接在浏览器中尝试时,它会成功

时间:2013-01-04 14:49:43

标签: java servlets httpconnection

以下代码段尝试将2个参数以及URL发送到servlet。但是当我尝试这个片段时,我收到一条消息:

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

     }
}

注意:

尝试上述代码段时返回的响应代码为 505

1 个答案:

答案 0 :(得分:1)

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