连接到URL失败,但当我直接在浏览器中尝试时,它成功了



下面的代码片段尝试将2个参数和一个URL一起发送给servlet。但是当我尝试这个代码片段时,我得到一条消息:

Connection to file server failed

但是如果我直接尝试URL:

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

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

相关内容

  • 没有找到相关文章

最新更新