Java 如何从 IO 异常中检测 404 响应代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22147277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to detect 404 response code from IO exception?
提问by NameSpace
How are you suppose to detect a 404 from an IO exception. I could just search the error message for "404", but is that the correct way? Anything more direct?
您打算如何从 IO 异常中检测 404。我可以只搜索“404”的错误消息,但这是正确的方法吗?还有更直接的吗?
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.Drive.Files.Update;
import com.google.api.services.drive.Drive;
File result = null;
try {
update = drive.files().update(driveId, file , mediaContent);
update.setNewRevision(true);
result = update.execute();
} catch (IOException e) {
Log.e(TAG, "file update exception, statusCode: " + update.getLastStatusCode());
Log.e(TAG, "file update exception, e: " + e.getMessage());
}
Log.e(TAG, "file update exception, statuscode " + update.getLastStatusCode());
03-03 05:04:31.738: E/System.out(31733): file update exception, statusCode: -1
03-03 05:04:31.738: E/System.out(31733): file update exception, e: 404 Not Found
03-03 05:04:31.738: E/System.out(31733): "message": "File not found: FileIdRemoved",
Answer: Aegan's comment below was correct, turns out you can subclass the the exception to a GoogleJsonResponseException and from there get the status code. The answer in this case ultimately depended on the fact I am using a GoogleClient, which generates a subclass of IO Exception that contains the status code.
回答:下面 Aegan 的评论是正确的,事实证明您可以将异常子类化为 GoogleJsonResponseException 并从那里获取状态代码。在这种情况下,答案最终取决于我使用 GoogleClient 的事实,它生成包含状态代码的 IO Exception 子类。
Example:
例子:
Try{
...
}catch (IOException e) {
if(e instanceof GoogleJsonResponseException){
int statusCode = ((GoogleJsonResponseException) e).getStatusCode();
//do something
}
}
采纳答案by Devrim
Handle HttpResponseException
:
处理HttpResponseException
:
catch (HttpResponseException hre) {
if (hre.getStatusCode() == 404) {
// TODO: Handle Http 404
}
}
Detail:AbstractGoogleClientRequest
creates exceptions.See source code
详细信息:AbstractGoogleClientRequest
创建异常。查看源代码
execute
method calls executeUnparsed
. executeUnparsed
creates exception with newExceptionOnError
. There you will see, it throws a HttpResponseException
(which is a subclass of IOException
)
execute
方法调用executeUnparsed
。executeUnparsed
创建异常newExceptionOnError
。在那里你会看到,它抛出一个HttpResponseException
(它是 的子类IOException
)
回答by Bosko Mijin
You should to get response error code.
你应该得到响应错误代码。
I made little example:
我做了一个小例子:
int code = con.getResponseCode();
if (code == HttpURLConnection.HTTP_NOT_FOUND) {
// Handle error
}
else {
// Do your work
}