/** * 重試處理 * 默認是重試3次 */ //禁用重試(參數:retryCount、requestSentRetryEnabled) HttpRequestRetryHandler requestRetryHandler = new DefaultHttpRequestRetryHandler(0, false); //自定義重試策略 HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { //Do not retry if over max retry count if (executionCount >= 3) { return false; } //Timeout if (exception instanceof InterruptedIOException) { return false; } //Unknown host if (exception instanceof UnknownHostException) { return false; } //Connection refused if (exception instanceof ConnectTimeoutException) { return false; } //SSL handshake exception if (exception instanceof SSLException) { return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); //Retry if the request is considered idempotent //如果請求類型不是HttpEntityEnclosingRequest,被認為是冪等的,那么就重試 //HttpEntityEnclosingRequest指的是有請求體的request,比HttpRequest多一個Entity屬性 //而常用的GET請求是沒有請求體的,POST、PUT都是有請求體的 //Rest一般用GET請求獲取數據,故冪等,POST用於新增數據,故不冪等 if (idempotent) { return true; } return false; } };