我遇到了最奇怪的 Tomcat 错误。我有一个使用 tomcat 在本地主机的端口 8080 上运行的 Web 应用程序,一切似乎都运行良好,没有错误等。但是,当我尝试使用 HttpURLConnection 类从另一个应用程序访问此 Web 应用程序时,我收到 404 错误。奇怪的是,当我在浏览器中输入相同的 URL 时,它返回 200 代码并具有有效响应。
我已经尝试/检查了这些帖子中的以下内容:post1 https://stackoverflow.com/questions/8279219/url-is-accessable-with-browser-but-still-filenotfoundexception-with-urlconnectio and post2 https://stackoverflow.com/questions/941628/urlconnection-filenotfoundexception-for-non-standard-http-port-sources
- 设置
User Agent
and Accept
标头。
- 我已经检查了响应正文(使用
HttpURLConnection.getInputStream()
也HttpURLConnection.getErrorStream()
,在 404 是不正确的返回代码的情况下)并且我确实收到了页面未找到响应。
- 我尝试过设置
connection.setDoOutput()
to true
and false
但这并没有帮助。
- 尝试改变
localhost
to 127.0.0.1
.
更多信息,我查看了Tomcat
访问日志,并且该请求似乎从未到达服务器(意味着该请求从未被记录)。但是,当我将 URL 放入浏览器(并获得有效响应)时,该请求确实会显示在日志中。
另一件事,我正在使用 eclipse 运行 tomcat。是的,该应用程序正在部署在服务器上。
另外,我发现有人似乎遇到了完全相同的问题here http://www.coderanch.com/t/490944/java/java/Bogus-HttpURLConnection,但没有解决方案,所以我将问题带到 SO! 的伟大社区!
编辑:调用应用程序的代码:
出于隐私原因,我隐藏了网址
public static void main(String[] args) {
final String url = "";
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setDoOutput(false);
System.out.println(con.getResponseCode());
System.out.println(getStringFromInputStream(con.getInputStream()));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("DONE");
}
是的,这确实适用于其他主机,例如谷歌。我得到的回应http://www.google.com
这是:
200
<!doctype html><html....>*bunch of html*</html>
DONE
回复http://localhost:8080/...
:
404
java.io.FileNotFoundException: *url*
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1674)
at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1672)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1670)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1243)
at Get.main(Get.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: java.io.FileNotFoundException: *url*
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1623)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)
at Get.main(Get.java:31)
... 5 more
DONE