RestTemplate設置超時時間及返回狀態(tài)碼非200處理
默認情況下使用RestTemplate如果返回結果的狀態(tài)碼是200的話就正常處理,否則都會拋出異常;
1.調試postForEntity請求
調試postForEntity請求的方法找到判斷響應結果狀態(tài)碼的方法是org.springframework.web.client.DefaultResponseErrorHandler類中的hasError方法
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
int rawStatusCode = response.getRawStatusCode();
HttpStatus statusCode = HttpStatus.resolve(rawStatusCode);
return (statusCode != null ? hasError(statusCode) : hasError(rawStatusCode));
}
代碼再往上跟蹤一級,如下:
protected void handleResponse(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
ResponseErrorHandler errorHandler = getErrorHandler();
boolean hasError = errorHandler.hasError(response);
if (logger.isDebugEnabled()) {
try {
int code = response.getRawStatusCode();
HttpStatus status = HttpStatus.resolve(code);
logger.debug("Response " + (status != null ? status : code));
}
catch (IOException ex) {
// ignore
}
}
if (hasError) {
errorHandler.handleError(url, method, response);
}
}
從上面的代碼可以看到是使用了RestTemplate的錯誤處理器,所以我們就可以想辦法自定義錯誤處理器;
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
RestTemplate restTemplate = new RestTemplate(factory);
ResponseErrorHandler responseErrorHandler = new ResponseErrorHandler() {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return true;
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
};
restTemplate.setErrorHandler(responseErrorHandler);
return restTemplate;
}zhi
只需要將hasError方法的返回值更改為true就可以了,以后不管狀態(tài)碼是200還是其它的都會返回結果;
2.設置超時時間
RestTemplate默認使用的是SimpleClientHttpRequestFactory工廠方法,看下它的超時時間是:
private int connectTimeout = -1; private int readTimeout = -1;
默認值都是-1,也就是沒有超時時間;
其底層是使用URLConnection,而URLConnection實際上時封裝了Socket,Socket我們知道是沒有超時時間限制的,所以我們必須設置超時時間,否則如果請求的URL一直卡死程序將會不可以運行下去;
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
//讀取超時5秒,默認無限限制,單位:毫秒
factory.setReadTimeout(5000);
//連接超時10秒,默認無限制,單位:毫秒
factory.setConnectTimeout(10000);
return factory;
}
以上就是RestTemplate設置超時時間及返回狀態(tài)碼非200處理的詳細內容,更多關于RestTemplate超時設置非200處理的資料請關注腳本之家其它相關文章!
相關文章
JAVA 多態(tài)操作----父類與子類轉換問題實例分析
這篇文章主要介紹了JAVA 多態(tài)操作----父類與子類轉換問題,結合實例形式分析了JAVA 多態(tài)操作中父類與子類轉換問題相關原理、操作技巧與注意事項,需要的朋友可以參考下2020-05-05
SpringBoot+@EnableScheduling使用定時器的常見案例
項目開發(fā)中經常需要執(zhí)行一些定時任務,本文主要介紹了SpringBoot+@EnableScheduling使用定時器的常見案例,具有一定的參考價值,感興趣的可以了解一下2023-09-09
hadoop的hdfs文件操作實現(xiàn)上傳文件到hdfs
這篇文章主要介紹了使用hadoop的API對HDFS上的文件訪問,其中包括上傳文件到HDFS上、從HDFS上下載文件和刪除HDFS上的文件,需要的朋友可以參考下2014-03-03

