简体   繁体   English

URLConnection抛出FileNotFoundException。 我怎么发现这是由404引起的?

[英]URLConnection throws a FileNotFoundException. How do I discover this was caused by a 404?

I've got this code: 我有这个代码:

String buildUrl = DEFAULT_HOST + "/job/" + jobName + "/" + buildNumber + API_PATH;
URLConnection connection = new URL(buildUrl).openConnection();
InputStream is = connection.getInputStream();

If that buildUrl results in a 404 response, that last line throws a FileNotFoundException . 如果该buildUrl导致404响应,则该最后一行抛出FileNotFoundException But, I want to know that the server returned a 404 because I don't trust that FileNotFoundException always means 404 and I want to do something special when 404s occur. 但是,我想知道服务器返回404,因为我不相信FileNotFoundException 总是意味着 404,我想在404s发生时做一些特别的事情。

How do I know when a 404 occurs when using a URLConnection ? 使用URLConnection时如何知道404何时发生?

first, cast to HttpURLConnection then call connection.connect() instead of getInputStream . 首先, HttpURLConnectionHttpURLConnection然后调用connection.connect()而不是getInputStream Once done, call getResponceCode() . 完成后,调用getResponceCode() If all is good, then you can get the input stream 如果一切顺利,那么您可以获得输入流

If you are ok with a 3rd party library then look at apache commons http client component project. 如果您对第三方库感到满意,那么请查看apache commons http客户端组件项目。 This library has much more user friendly http api than native url connection api in jdk. 这个库比jdk中的本机u​​rl连接api具有更多用户友好的http api。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM