【发布时间】:2011-07-19 18:02:48
【问题描述】:
我正在尝试使用 HttpURLConnection(用于在 java 中使用 cUrl)向 url 发送 post 请求。 请求的内容是 xml,在终点,应用程序处理 xml 并将记录存储到数据库中,然后以 xml 字符串的形式发回响应。该应用程序在本地托管在 apache-tomcat 上。
当我从终端执行此代码时,会按预期将一行添加到数据库中。但是从连接中获取InputStream的时候抛出异常如下
java.io.FileNotFoundException: http://localhost:8080/myapp/service/generate
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1401)
at org.kodeplay.helloworld.HttpCurl.main(HttpCurl.java:30)
这里是代码
public class HttpCurl {
public static void main(String [] args) {
HttpURLConnection con;
try {
con = (HttpURLConnection) new URL("http://localhost:8080/myapp/service/generate").openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
File xmlFile = new File("test.xml");
String xml = ReadWriteTextFile.getContents(xmlFile);
con.getOutputStream().write(xml.getBytes("UTF-8"));
InputStream response = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(response));
for (String line ; (line = reader.readLine()) != null;) {
System.out.println(line);
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
它令人困惑,因为异常被跟踪到InputStream response = con.getInputStream(); 行,并且似乎没有涉及 FileNotFoundException 的任何文件。
当我尝试直接打开与 xml 文件的连接时,它不会抛出此异常。
服务应用使用 spring 框架和 Jaxb2Marshaller 创建响应 xml。
ReadWriteTextFile 类取自here
谢谢。
编辑: 嗯,它把数据保存在DB中,同时发回404响应状态码。
我还尝试使用 php 进行 curl 并打印出 CURLINFO_HTTP_CODE,结果是 200。
关于如何调试它的任何想法?服务和客户端都在本地服务器上。
已解决: 在参考 SO 本身的answer 后,我可以解决问题。
似乎 HttpURLConnection 在连接到具有非标准端口的 url 时总是返回 404 响应。
添加这些行解决了它
con.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
con.setRequestProperty("Accept","*/*");
【问题讨论】:
-
“当我从终端执行此代码时”- 哪个代码?目前尚不清楚哪些有效与哪些无效。
-
HttpCurl 是具有此 main 方法的类的名称。这个类是从终端编译运行的
-
我遇到了同样的问题,但这里的解决方案都不起作用。我最终发现这是 Java 1.7.0_05 的问题,并更新到最新版本 1.7.0_21,问题就消失了。我也意识到这个问题在 Java 1.6 中没有出现。对于仍然卡住的人,仅供参考。
-
伙计们!请参阅问题的“已解决”评论而不是答案!
标签: java inputstream httpurlconnection filenotfoundexception