使用httpClient 調起https url接口


******遇到的問題*******
一、ssl證書信任,解決方式信任全部證書
二、生成請求體調用httpPost.setEntity()時輸出的參數格式有誤,有多種Entity能夠選擇(經常使用 StringEntity、UrlEncodedFormEntity、FileEntity等),根據參數格式選擇合理的json

1、LookAlikeHttpService 
/**
 * 請求lookAlike HTTP調起工具類
 *
 * @author zhaoxinyu
 * @create 2018/04/26
 */
@Service("lookAlikeHttpService")
public class LookAlikeHttpService extends DefaultHttpClient {
    private final String charset = "utf-8";
    private static final String HTTP = "http";
    private static final String HTTPS = "https";
    private static SSLConnectionSocketFactory sslsf = null;
    private static PoolingHttpClientConnectionManager cm = null;
    private static SSLContextBuilder builder = null;app

    static {
        try {
            builder = new SSLContextBuilder();
            // 所有信任 不作身份鑑定
            builder.loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            });
            sslsf = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register(HTTP, new PlainConnectionSocketFactory())
                    .register(HTTPS, sslsf)
                    .build();
            cm = new PoolingHttpClientConnectionManager(registry);
            cm.setMaxTotal(200);//max connection
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * httpClient post請求
     * @param url 請求url
     * @param param 請求參數 form提交適用
     * @return 可能爲空 須要處理
     * @throws Exception
     *
     */
    public static String sendHttpsPost(String  url, String param) throws Exception {
        String result = "";
        CloseableHttpClient httpClient = null;
        try {
            httpClient = getHttpClient();
            HttpPost httpPost = new HttpPost(url);
            /**
             * 設置請求頭
             */
            httpPost.addHeader("Content-Type", "application/json");
            httpPost.addHeader("userName","aml4rest");
            httpPost.addHeader("passWord","3er4#ER$3er4#ER$12");
            /**
             *  設置請求參數
             */
            StringEntity stringEntity = new StringEntity(param, "utf-8");
            httpPost.setEntity(stringEntity);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity resEntity = httpResponse.getEntity();
                result = EntityUtils.toString(resEntity);
            } else {
                result = readHttpResponse(httpResponse);
            }
            
        } catch (Exception e) {
            System.out.println("send lookalike http post request failed, HttpException"+e);
            throw e;
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
        }
        System.out.println("lookAlikeHttpService doPost(..); result=" + result + ";");
        return result;
    }ide

    public String readFromInputStream(InputStream in, String charset) throws UnsupportedEncodingException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(in,charset), 2048);
        LineIterator li = new LineIterator(br);
        while (li.hasNext())
        {
            if (sb.length() > 5000)
            {
                continue;
            }
            sb.append(li.next());
        }
        return sb.toString();
    }
    
    public static CloseableHttpClient getHttpClient() throws Exception {
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .setConnectionManager(cm)
                .setConnectionManagerShared(true)
                .build();
        return httpClient;
    }
    
    public static String readHttpResponse(HttpResponse httpResponse)
            throws ParseException, IOException {
        StringBuilder builder = new StringBuilder();
        // 獲取響應消息實體
        HttpEntity entity = httpResponse.getEntity();
        // 響應狀態
        builder.append("status:" + httpResponse.getStatusLine());
        builder.append("headers:");
        HeaderIterator iterator = httpResponse.headerIterator();
        while (iterator.hasNext()) {
            builder.append("\t" + iterator.next());
        }
        // 判斷響應實體是否爲空
        if (entity != null) {
            String responseString = EntityUtils.toString(entity);
            builder.append("response length:" + responseString.length());
            builder.append("response content:" + responseString.replace("\r\n", ""));
        }
        return builder.toString();
    }
}工具

2、組裝參數方法
/**
 * 根據任務信息調起任務
 */
public JSONObject invokeAlgorithm(TaskInfo taskInfo) throws Exception {
    String path = propertyUtil.getProperty("invokePath");
    
    String dataPath = propertyUtil.getProperty("hadoopBasePath")+ File.separator +"hc_data_"+String.valueOf(taskInfo.gettId())+".txt";
    String schemaPath = propertyUtil.getProperty("hadoopBasePath")+ File.separator +"hc_schema_"+String.valueOf(taskInfo.gettId())+".txt";
    String labelFeatureId = String.valueOf((customerInfoService.getCustomerListBytId(String.valueOf(taskInfo.gettId())).size()+1));oop

    JSONObject params = new JSONObject();
    params.put("dataPath", dataPath);
    params.put("schemaPath", schemaPath);
    params.put("delimiter", "|");
    params.put("primaryKeyId", "0");
    params.put("businessLabel", "lookalike");
    params.put("businessId", String.valueOf(taskInfo.getsId()));
    params.put("labelFeatureId", labelFeatureId);post

    JSONObject parameter = new JSONObject();
    parameter.put("parameter",params);
    
    JSONObject result = JSONObject.fromObject(lookAlikeHttpService.sendHttpsPost(path,parameter.toString()));
    return result;
}ui

相關文章
相關標籤/搜索