http請求工具類HttpClientUtil(get使用body,post亂碼問題解決)

最近很多發送http請求的需求存在,書寫下util

1:配置需要的依賴

在pom.xml中配置http相關依賴

		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore</artifactId>
		</dependency>

2:因部分特殊(蠢狗)對接方需要get請求使用body請求體,附上重寫的類

/**
 * @author afresh
 * @description 封裝httpget可以攜帶body參數
 * @since 2020/2/25 11:08 上午
 */
public class HttpGetWithBody extends HttpEntityEnclosingRequestBase {

    public static final String METHOD_NAME = "GET";

    @Override
    public String getMethod() { return METHOD_NAME; }

    public HttpGetWithBody(final String uri) {
        super();
        setURI(URI.create(uri));
    }
    public HttpGetWithBody(final URI uri) {
        super();
        setURI(uri);
    }
    public HttpGetWithBody() { super(); }
}

若其他請求例如delete也需要使用body請求體,則將METHD_NAME改爲對應的值即可 例如:“DELETE”

3:完整util代碼 可直接使用

注意一點:常見的post請求亂碼問題需要使用 下述代碼(只設置CONTENT_TYPE的編碼格式不生效)

httpPost.setEntity(new StringEntity(param, ContentType.create("application/json", "utf-8")));
public class HttpCommonClientUtils {

    private static PoolingHttpClientConnectionManager pccm= null;

    private static final Logger logger = LoggerFactory.getLogger(HttpCommonClientUtils.class);

    private static final String CONTENT_TYPE = "application/json;charset=utf-8";

    static {
        try{
            //設置訪問協議
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                //信任所有
                public boolean isTrusted(X509Certificate[] chain,
                                         String authType) throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslsf)
                    .build();

            pccm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            pccm.setDefaultMaxPerRoute(30); //每個主機的最大並行鏈接數
            pccm.setMaxTotal(200);
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
    }

    /**
     * 獲取連接
     * @return
     */
    private static HttpClient getHttpClient() {

        //設置連接超時時間
        int REQUEST_TIMEOUT = 20*1000;  //設置請求超時20秒鐘
        int SO_TIMEOUT = 20*1000;       //設置等待數據超時時間20秒鐘
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setSocketTimeout(SO_TIMEOUT)
                .setConnectTimeout(REQUEST_TIMEOUT)
                .setConnectionRequestTimeout(REQUEST_TIMEOUT)
                .setStaleConnectionCheckEnabled(true)
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(pccm).setDefaultRequestConfig(defaultRequestConfig).build();
        return httpClient;
    }

    /**
     * 發起請求並返回結果POST
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String executePost(String url, Object params, String authorization)  throws  Exception {
        String result = null;
        String setUrl=url;
        String param= JSONObject.toJSONString(params);
        logger.info("請求url:"+url);
        logger.info("請求入參:"+param);
        HttpPost httpPost = new HttpPost(setUrl);
        httpPost.setEntity(new StringEntity(param, ContentType.create("application/json", "utf-8")));
        httpPost.setHeader("Content-Type","application/json");
        if(StringUtils.isNotBlank(authorization)) {
            httpPost.setHeader("Authorization",authorization);
        }
        try {
            HttpResponse response = getHttpClient().execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            logger.info("statusCode:"+statusCode);
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED || statusCode == HttpStatus.SC_BAD_REQUEST) {
                result = getStreamAsString(response.getEntity().getContent(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(500, "網絡繁忙, 請稍後再試");
        }
        return result;
    }


    /**
     * 發起請求並返回結果GET
     * @param url
     * @return
     * @throws Exception
     */
    public static String executeGet(String url, String authorization) throws BaseException {
        logger.info("請求url:"+url);
        HttpGet httpGet = new HttpGet(url);

        HttpResponse response = null;
        try {
            httpGet.setHeader("Content-Type",CONTENT_TYPE);
            if(StringUtils.isNotBlank(authorization)) {
                httpGet.setHeader("Authorization",authorization);
            }
            response = getHttpClient().execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            logger.info("statusCode:"+statusCode);
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED || statusCode == HttpStatus.SC_BAD_REQUEST) {
                return getStreamAsString(response.getEntity().getContent(), "UTF-8");
            } else {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new BaseException(500, "網絡繁忙, 請稍後再試");
        }
    }


    public static String executeGetWithParam(String url, Object param, String authorization){
        JSONObject params = (JSONObject) JSONObject.toJSON(param);
        logger.info("請求地址:{}, 請求參數:{}", url, params.toJSONString());

        StringBuffer paramsStr = new StringBuffer("?");
        String paramResult = null;
        if (!params.isEmpty()) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (entry.getValue() != null){
                    paramsStr.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }
            }
            paramResult = paramsStr.substring(0, paramsStr.length() - 1);
        }

        if (paramResult != null) {
            url = url + paramResult;
        }

        String result = null;
        try {
            result = HttpCommonClientUtils.executeGet(url,authorization);
        } catch (BaseException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 發起請求並返回結果get(body請求體)
     * @param url
     * @return
     * @throws Exception
     */
    public static String executeGethWithBody(String url, Object params, String authorization)  throws  Exception {
        String result = null;
        HttpGetWithBody httpGet = new HttpGetWithBody(url);
        String param= JSONObject.toJSONString(params);
        logger.info("請求url:"+url);
        logger.info("請求入參:"+param);
        httpGet.setEntity(new StringEntity(param, ContentType.create("application/json", "utf-8")));
        httpGet.setHeader("Content-Type",CONTENT_TYPE);
        if(StringUtils.isNotBlank(authorization)) {
            httpGet.setHeader("Authorization",authorization);
        }
        try {
            HttpResponse response = getHttpClient().execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            logger.info("statusCode:"+statusCode);
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
                result = getStreamAsString(response.getEntity().getContent(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(500, "網絡繁忙, 請稍後再試");
        }
        return result;
    }

    /**
     * 發起請求並返回結果PUT
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String executePut(String url, Object params, String authorization)  throws  Exception {
        String result = null;
        String setUrl=url;
        String param= JSONObject.toJSONString(params);
        logger.info("請求url:"+url);
        logger.info("請求入參:"+param);
        HttpPut httpPut = new HttpPut(setUrl);
        httpPut.setEntity(new StringEntity(param,ContentType.create("application/json", "utf-8")));
        httpPut.setHeader("Content-Type",CONTENT_TYPE);
        if(StringUtils.isNotBlank(authorization)) {
            httpPut.setHeader("Authorization",authorization);
        }
        try {
            HttpResponse response = getHttpClient().execute(httpPut);
            int statusCode = response.getStatusLine().getStatusCode();
            logger.info("statusCode:"+statusCode);
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
                result = getStreamAsString(response.getEntity().getContent(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(500, "網絡繁忙, 請稍後再試");
        }
        return result;
    }


    /**
     * 發起請求並返回結果DELETE
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String executeDel(String url, Object params, String authorization)  throws  Exception {
        String result = null;
        String setUrl=url;
        String param= JSONObject.toJSONString(params);
        HttpDelete httpdelete = new HttpDelete(setUrl);
        httpdelete.setHeader("Content-Type",CONTENT_TYPE);
        if(StringUtils.isNotBlank(authorization)) {
            httpdelete.setHeader("Authorization",authorization);
        }
        try {
            HttpResponse response = getHttpClient().execute(httpdelete);
            int statusCode = response.getStatusLine().getStatusCode();
            logger.info("statusCode:"+statusCode);
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
                result = getStreamAsString(response.getEntity().getContent(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(500, "網絡繁忙, 請稍後再試");
        }
        return result;
    }

    /**
     * 發起請求並返回結果DELETE(body請求體)
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String executeDelWithBody(String url, Object params, String authorization)  throws  Exception {
        String result = null;
        String setUrl=url;
        String param= JSONObject.toJSONString(params);
        HttpDeleteWithBody httpdelete = new HttpDeleteWithBody(setUrl);
        httpdelete.setEntity(new StringEntity(param,ContentType.create("application/json", "utf-8")));
        httpdelete.setHeader("Content-Type",CONTENT_TYPE);
        if(StringUtils.isNotBlank(authorization)) {
            httpdelete.setHeader("Authorization",authorization);
        }
        try {
            HttpResponse response = getHttpClient().execute(httpdelete);
            int statusCode = response.getStatusLine().getStatusCode();
            logger.info("statusCode:"+statusCode);
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
                result = getStreamAsString(response.getEntity().getContent(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(500, "網絡繁忙, 請稍後再試");
        }
        return result;
    }

    /**
     * 發起請求並返回結果PATCH
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String executePatch(String url, Object params, String authorization)  throws  Exception {
        String result = null;
        String setUrl=url;
        String param= JSONObject.toJSONString(params);
        HttpPatch httpPatch = new HttpPatch(setUrl);
        httpPatch.setEntity(new StringEntity(param,ContentType.create("application/json", "utf-8")));
        httpPatch.setHeader("Content-Type",CONTENT_TYPE);
        if(StringUtils.isNotBlank(authorization)) {
            httpPatch.setHeader("Authorization",authorization);
        }
        try {
            HttpResponse response = getHttpClient().execute(httpPatch);
            int statusCode = response.getStatusLine().getStatusCode();
            logger.info("statusCode:"+statusCode);
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
                result = getStreamAsString(response.getEntity().getContent(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(500, "網絡繁忙, 請稍後再試");
        }
        return result;
    }

    /**
     * 將流轉換爲字符串
     * @param stream
     * @param charset
     * @return
     * @throws IOException
     */
    private static String getStreamAsString(InputStream stream, String charset) throws IOException {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset), 8192);
            StringWriter writer = new StringWriter();

            char[] chars = new char[8192];
            int count = 0;
            while ((count = reader.read(chars)) > 0) {
                writer.write(chars, 0, count);
            }

            return writer.toString();
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    }

    /**
     *
     * @param requestParam
     * @param coder
     * @return
     */
    private static String getRequestParamString(Map<String, String> requestParam, String coder) {
        if (null == coder || "".equals(coder)) {
            coder = "UTF-8";
        }
        StringBuffer sf = new StringBuffer("");
        String reqstr = "";
        if (null != requestParam && 0 != requestParam.size()) {
            for (Map.Entry<String, String> en : requestParam.entrySet()) {
                try {
                    sf.append(en.getKey()
                            + "="
                            + (null == en.getValue() || "".equals(en.getValue()) ? "" : URLEncoder
                            .encode(en.getValue(), coder)) + "&");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    return "";
                }
            }
            reqstr = sf.substring(0, sf.length() - 1);
        }
        return reqstr;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章