1. 程式人生 > >企業微信介面開發之使用httpclient實現https請求

企業微信介面開發之使用httpclient實現https請求

    接上篇,企業微信的api不贅述,使用的是https協議.由於資訊也不是很重要,就沒有考慮安全問題,直接使用httpclient繞過證書認證實現功能

1.引入httpclient依賴

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
<version>4.1.3</version> </dependency>

2.實現自己的Cilent 繼承 DefaultHttpCilent 繞過證書認證

public class SSLClient extends DefaultHttpClient {
    public SSLClient() throws Exception{
        super();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
            @Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers
() { return null; } }; ctx.init(null, new TrustManager[]{tm}, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = this.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", 443, ssf)); } }

3.提供幫助類HttpClientUtils提供post與get方法

public class HttpClientUtils {

    public static String doPost(String url,String jsonstr,String charset){
        HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
        try{
            httpClient = new SSLClient();
httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
StringEntity se = new StringEntity(jsonstr, "UTF-8");
se.setContentType("text/json");
se.setContentEncoding(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
httpPost.setEntity(se);
HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
}
            }
        }catch(Exception ex){
            ex.printStackTrace();
}
        return result;
}

    public static String doGet(String url, String charset){
        HttpClient httpClient = null;
HttpGet httpGet = null;
String result = null;
        try{
            httpClient = new SSLClient();
httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
}
            }
        }catch (Exception e){
            e.printStackTrace();
}
        return result;
}
}
至此直接呼叫HttpCilentUtils doPost或doGet方法 傳入引數,就能呼叫https介面啦