【发布时间】: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