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

标签 java servlets httpconnection

以下代码片段尝试将 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()方法。

关于java - 连接到URL失败,但是当我直接在浏览器中尝试时,它成功了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14159341/

相关文章:

java - 如何以更简单的方式从 XML 文件中获取单个属性

java - 在没有表单的情况下将数据从 servlet 传递到 jsp?

java - 使用HttpURLConnection读取elasticsearch的输出时出现FileNotFoundException

image - 在 BlackBerry 5.0 中显示静态 Google map 图像

java - J2ME HttpConnection 无限重定向

java - 在android中的数据报套接字上发送和接收UDP数据包

java - jackson/json 模式 - 用外部 json 模式生成器模块替换 ISO8601Utils

java - try/catch block 捕获异常有什么意义?

java - file.createNewFile() 创建最后修改时间早于实际创建时间的文件

java - 正确命名 Java Google App Engine 项目的方法