http client org.apache.http.NoHttpResonse Exception:host:ポートfailed to repondエラーの原因と解決方法

3491 ワード

failed to repond  理由は: 
httpclient前にサービス端末とのリンクが失効しました.(例えば、tomcatのデフォルトのkeep-alive timeout:20 s)、再度接続池からこの故障リンクを取って要求すると、エラーが発生します.
具体的には参考できます.https://blog.csdn.net/xiaoduanayu/article/details/78386508
解決の考え方:http接続は多重化できません.
解決コード:
httpPost.setHeader("Connection", "close");
package com.phkj.equipment.util;


import com.aliyun.oss.common.utils.HttpUtil;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.SocketTimeoutException;

public class HttpClientUtils {
    private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
    private static final CloseableHttpClient httpclient = HttpClients.createMinimal();
    private static final String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36";

    /**
     *   HttpPost  ,   json    * * @param url * @param jsonStr * @return
     */
    public static String sendPost(String url, String jsonStr, int requestTimeout, int socketTimeout, int connectTimeout) throws ConnectTimeoutException, SocketTimeoutException, IOException, Exception {
        if (requestTimeout == 0)
            requestTimeout = 3000;
        if (socketTimeout == 0)
            requestTimeout = 3000;
        if (connectTimeout == 0)
            connectTimeout = 3000;

        String result = null;
        //      
        StringEntity entity = new StringEntity(jsonStr, Consts.UTF_8);
        //   content-type
        entity.setContentType("application/json");
        HttpPost httpPost = new HttpPost(url);
        //      3 
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(requestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
        httpPost.setConfig(requestConfig);
        //           
        httpPost.setHeader("User-Agent", userAgent);
         //        
        httpPost.setHeader("Connection", "close");
        //       
        httpPost.setHeader("Accept", "application/json");
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            result = EntityUtils.toString(httpEntity, "utf-8");
        } catch (ConnectTimeoutException ex) {
            throw ex;
        } catch (SocketTimeoutException e) {
            throw e;
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            throw e;
        } finally {
            //   CloseableHttpResponse
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
        return result;
    }
}