我有一个Java客户端应用程序,它向服务器API发出请求。
如果在请求/响应期间出现网络错误,如果 任何机会 服务器收到请求,我需要假设已收到请求。
但是,如果我<100>确定服务器没有收到请求,我需要将请求视为失败。
我的问题是,是否存在一些关于java.net包抛出的IOException子类的类型和/或细节的逻辑,我可以用它来确定请求 最终是否未到达服务器 (例如,未创建套接字或未发送数据)?
目前我有以下内容,但正如您所看到的,这不是全面的,也不是非常令人放心(使用异常消息来区分读取和关闭连接超时):
/**
* This returns true if the exception is a network timeout that happened BEFORE the server received any data
* @param e The exception that was thrown
* @return true if the exception is a network timeout that happened BEFORE the server received any data
*/
public static boolean isDefinitivePreConnectionNetworkError(Exception e) {
//return true for all java.net.SocketException and java.io.InterruptedIOException that don't have the word "read" or "closed" in their message (case insensitive)
if(!e.getClass().isAssignableFrom(IOException.class) || ExceptionUtils.getRootCause(e).getClass().isAssignableFrom(IOException.class)) {
return false;
}
String message = e.getMessage();
Throwable eRoot = ExceptionUtils.getRootCause(e);
String messageRoot = eRoot == null ? message : eRoot.getMessage();
message = message == null ? "" : message.toLowerCase();
messageRoot = messageRoot == null ? "" : messageRoot.toLowerCase();
if(messageRoot.contains("read")
|| message.contains("read")
|| messageRoot.contains("closed")
|| message.contains("closed")) {
return false;
}
return (eRoot instanceof java.net.SocketException
|| eRoot instanceof java.io.InterruptedIOException
|| e instanceof java.net.SocketException
|| e instanceof java.io.InterruptedIOException
);
}