1. 程式人生 > 資訊 >中汽協:預計 2022 年新能源汽車銷量為 500 萬輛,同比增長 47%

中汽協:預計 2022 年新能源汽車銷量為 500 萬輛,同比增長 47%

  1. pom引入jar
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore</artifactId>
		</dependency>    

  2. 工具類程式碼

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; } }

  3.HttpGetWithBody工具類

/**
 * @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(); }
}

轉自:https://blog.csdn.net/weixin_38373006/article/details/105097343