HTTPS接口的調用

//<httpclient 版本>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.5</version>
        </dependency>java

//工具類apache

package com.kidswang.mabaobang.util;app

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;socket

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;工具

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;post

public class HttpClients {編碼

    /**
     * 向HTTPS地址發送POST請求
     * @param reqURL 請求地址
     * @param params 請求參數
     * @return 響應內容
     */
    @SuppressWarnings("all")
    public static String sendSSLPostRequest(String reqURL,
            Map<String, String> params) {
        long responseLength = 0; // 響應長度
        String responseContent = null; // 響應內容
        HttpClient httpClient = new DefaultHttpClient(); // 建立默認的httpClient實例
        // HttpClient httpClient = new HttpClient();
        X509TrustManager xtm = new X509TrustManager() { // 建立TrustManager
            public void checkClientTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException {
            }url

            public void checkServerTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException {
            }.net

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        try {
            // TLS1.0與SSL3.0基本上沒有太大的差異,可粗略理解爲TLS是SSL的繼承,但它們使用的是相同的SSLContext
            SSLContext ctx = SSLContext.getInstance("TLS");code

            // 使用TrustManager來初始化該上下文,TrustManager只是被SSL的Socket
            ctx.init(null, new TrustManager[] { xtm }, null);

            // 建立SSLSocketFactory
            SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);

            // httpClient.getParams().se
            // 經過SchemeRegistry將SSLSocketFactory註冊到咱們的HttpClient
            httpClient.getConnectionManager().getSchemeRegistry()
                    .register(new Scheme("https", 443, socketFactory));

            HttpPost httpPost = new HttpPost(reqURL); // 建立HttpPost
            List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 構建POST請求的表單參
            for (Map.Entry<String, String> entry : params.entrySet()) {
                formParams.add(new BasicNameValuePair(entry.getKey(), entry
                        .getValue()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));

            HttpResponse response = httpClient.execute(httpPost); // 執行POST請求
            HttpEntity entity = response.getEntity(); // 獲取響應實體

            if (null != entity) {
                responseLength = entity.getContentLength();
                responseContent = EntityUtils.toString(entity, "UTF-8");
                EntityUtils.consume(entity); // Consume response content
            }

        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpClient.getConnectionManager().shutdown(); // 關閉鏈接,釋放資源
            return responseContent;
        }
    }

    /**
     * 發送POST請求
     * @param reqURL 請求URL
     * @param params post參數
     * @return
     * @Description:
     */
    @SuppressWarnings("finally")
    public static String sendPostRequest(String reqURL,
            Map<String, String> params) {
        long responseLength = 0; // 響應長度
        String responseContent = null; // 響應內容
        HttpClient httpClient = new DefaultHttpClient(); // 建立默認的httpClient實例
        // HttpClient httpClient = new HttpClient();
        try {

            HttpPost httpPost = new HttpPost(reqURL); // 建立HttpPost

            List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 構建POST請求的表單參
            for (Map.Entry<String, String> entry : params.entrySet()) {
                formParams.add(new BasicNameValuePair(entry.getKey(), entry
                        .getValue()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));

            HttpResponse response = httpClient.execute(httpPost); // 執行POST請求
            HttpEntity entity = response.getEntity(); // 獲取響應實體

            if (null != entity) {
                responseLength = entity.getContentLength();
                responseContent = EntityUtils.toString(entity, "UTF-8");
                EntityUtils.consume(entity); // Consume response content
            }

        } catch (UnsupportedEncodingException e) {             e.printStackTrace();         } catch (ClientProtocolException e) {             e.printStackTrace();         } catch (ParseException e) {             e.printStackTrace();         } catch (IOException e) {             e.printStackTrace();         } finally {             httpClient.getConnectionManager().shutdown(); // 關閉鏈接,釋放資源             return responseContent;         }     }               /**       * 下載文件保存到本地       * @param path  文件保存位置       * @param url  文件地址       * @throws IOException       */       public static void downloadFile(String path, String url) throws IOException {           HttpClient client = null;           try {               // 建立HttpClient對象               client = new DefaultHttpClient();               // 得到HttpGet對象               HttpGet httpGet = getHttpGet(url, null, null);               // 發送請求得到返回結果               HttpResponse response = client.execute(httpGet);               // 若是成功               if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {                   byte[] result = EntityUtils.toByteArray(response.getEntity());                 /**                 InputStream sbs = new ByteArrayInputStream(result);                  BufferedOutputStream bw = null;                   try {                       // 建立文件對象                       File f = new File(path);                       // 建立文件路徑                       if (!f.getParentFile().exists())                           f.getParentFile().mkdirs();                       // 寫入文件                       bw = new BufferedOutputStream(new FileOutputStream(path));                       bw.write(result);                   } catch (Exception e) {                       e.printStackTrace();                   } finally {                       try {                           if (bw != null)                               bw.close();                       } catch (Exception e) {                           e.printStackTrace();                     }                   }                 **/               }             // 若是失敗               else {                   StringBuffer errorMsg = new StringBuffer();                   errorMsg.append("httpStatus:");                   errorMsg.append(response.getStatusLine().getStatusCode());                   errorMsg.append(response.getStatusLine().getReasonPhrase());                   errorMsg.append(", Header: ");                   Header[] headers = response.getAllHeaders();                   for (Header header : headers) {                       errorMsg.append(header.getName());                       errorMsg.append(":");                       errorMsg.append(header.getValue());                   }                   System.out.println("HttpResonse Error:" + errorMsg);               }           } catch (ClientProtocolException e) {               e.printStackTrace();               throw e;           } catch (IOException e) {               e.printStackTrace();               throw e;           } finally {               try {                   client.getConnectionManager().shutdown();               } catch (Exception e) {                   e.printStackTrace();              }           }       }            /**       * 下載文件字節碼      * @param path  文件保存位置       * @param url  文件地址       * @throws IOException       */       public static byte[] downloadFileBytes(String url){           HttpClient client = null;           byte[] byteData = null;         try {               // 建立HttpClient對象               client = new DefaultHttpClient();               // 得到HttpGet對象               HttpGet httpGet = getHttpGet(url, null, null);               // 發送請求得到返回結果               HttpResponse response = client.execute(httpGet);               // 若是成功               if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {                 byteData = EntityUtils.toByteArray(response.getEntity());                 InputStream sbs = new ByteArrayInputStream(byteData);             }         } catch (ClientProtocolException e) {               e.printStackTrace();           } catch (IOException e) {               e.printStackTrace();           } finally {             try {                   client.getConnectionManager().shutdown();               } catch (Exception e) {                   e.printStackTrace();              }           }         return byteData;     }            /**       * 得到HttpGet對象       * @param url  請求地址       * @param params 請求參數       * @param encode 編碼方式       * @return HttpGet對象       */       private static HttpGet getHttpGet(String url, Map<String, String> params,               String encode) {           StringBuffer buf = new StringBuffer(url);           if (params != null) {               // 地址增長?或者&               String flag = (url.indexOf('?') == -1) ? "?" : "&";               // 添加參數               for (String name : params.keySet()) {                   buf.append(flag);                   buf.append(name);                   buf.append("=");                   try {                       String param = params.get(name);                       if (param == null) {                           param = "";                       }                       buf.append(URLEncoder.encode(param, encode));                   } catch (UnsupportedEncodingException e) {                       e.printStackTrace();                   }                   flag = "&";               }           }           HttpGet httpGet = new HttpGet(buf.toString());           return httpGet;       }   }  

相關文章
相關標籤/搜索