方式一:java
HttpUtilapache
package com.weixinsdk.utils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; public class HttpUtil { private static Logger log = Logger.getLogger(HttpUtil.class); /** * 發送GET請求 * @param isHttps * 是否https * @param url * 請求地址 * @return 響應結果 */ public static String doGet(boolean isHttps, String url) { CloseableHttpClient httpClient = null; try { if (!isHttps) { httpClient = HttpClients.createDefault(); } else { httpClient = createSSLInsecureClient(); } HttpGet httpget = new HttpGet(url); // HttpGet設置請求頭的兩種種方式 // httpget.addHeader(new BasicHeader("Connection", "Keep-Alive")); httpget.addHeader("Connection", "Keep-Alive"); Header[] heads = httpget.getAllHeaders(); for (int i = 0; i < heads.length; i++) { System.out.println(heads[i].getName() + "-->" + heads[i].getValue()); } CloseableHttpResponse response = httpClient.execute(httpget); // 判斷狀態行 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); if (entity != null) { String out = EntityUtils.toString(entity, "UTF-8"); return out; } } } catch (ClientProtocolException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } finally { try { if (null != httpClient) { httpClient.close(); } } catch (IOException e) { log.error("httpClient.close()異常"); } } return null; } /** * 發送POST請求 * @param isHttps * 是否https * @param url * 請求地址 * @param data * 請求實體內容 * @param contentType * 請求實體內容的類型 * @return 響應結果 */ public static String doPost(boolean isHttps, String url, String data, String contentType) { CloseableHttpClient httpClient = null; try { if (!isHttps) { httpClient = HttpClients.createDefault(); } else { httpClient = createSSLInsecureClient(); } HttpPost httpPost = new HttpPost(url); // HttpPost設置請求頭的兩種種方式 // httpPost.addHeader(new BasicHeader("Connection", "Keep-Alive")); // httpPost.addHeader("Connection", "Keep-Alive"); // UrlEncodedFormEntity處理鍵值對格式請求參數 // List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); // new UrlEncodedFormEntity(list, "UTF-8"); if (null != data) { // StringEntity處理任意格式字符串請求參數 StringEntity stringEntity = new StringEntity(data, "UTF-8"); stringEntity.setContentEncoding("UTF-8"); if (null != contentType) { stringEntity.setContentType(contentType); } else { stringEntity.setContentType("application/json"); } httpPost.setEntity(stringEntity); } // 設置請求和傳輸超時時間 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build(); httpPost.setConfig(requestConfig); HttpResponse response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); if (entity != null) { String out = EntityUtils.toString(entity, "UTF-8"); return out; } } } catch (UnsupportedEncodingException e) { log.error(e); } catch (ClientProtocolException e) { e.printStackTrace(); log.error("鏈接超時:" + url); } catch (IOException e) { e.printStackTrace(); log.error("IO異常:" + url); } finally { try { if (null != httpClient) { httpClient.close(); } } catch (IOException e) { log.error("httpClient.close()異常"); } } return null; } /** * Https請求對象,信任全部證書 * * @return CloseableHttpClient */ public static CloseableHttpClient createSSLInsecureClient() { 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); return HttpClients.custom().setSSLSocketFactory(sslsf).build(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } return HttpClients.createDefault(); } /** * * 測試doGet方法,獲取access_token * @param args */ public static void main(String[] args) { String restu = doGet(true, "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx6c797fccab90c81f&secret=fa226e54468b28ece341c2451142ba0d"); System.out.println(restu); } }
方式二:json
HTTPClientUtilapi
package com.weixinsdk.utils; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.ConnectException; import java.net.URL; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import com.alibaba.fastjson.JSONObject; public class HTTPSUtil { /** * 發起https請求並獲取結果 * * @param requestUrl 請求地址 * @param requestMethod 請求方式(GET、POST) * @param outputStr 提交的數據 * @return JSONObject(經過JSONObject.get(key)的方式獲取json對象的屬性值) */ public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) { JSONObject jsonObject = null; StringBuffer buffer = new StringBuffer(); try { // 建立SSLContext對象,並使用咱們指定的信任管理器初始化 TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // 從上述SSLContext對象中獲得SSLSocketFactory對象 SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(); httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); // 設置請求方式(GET/POST) httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect(); // 當有數據須要提交時 if (null != outputStr) { OutputStream outputStream = httpUrlConn.getOutputStream(); // 注意編碼格式,防止中文亂碼 outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); } // 將返回的輸入流轉換成字符串 InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); // 釋放資源 inputStream.close(); inputStream = null; httpUrlConn.disconnect(); // jsonObject = JSONObject.fromObject(buffer.toString()); jsonObject = (JSONObject) JSONObject.parse(buffer.toString()); } catch (ConnectException ce) { } catch (Exception e) { } return jsonObject; } }
發送Http請求,返回Json數據進行解析app
/** * * fastjson:Http請求Get返回JSONObject * @param url * @return */ @SuppressWarnings("deprecation") public static com.alibaba.fastjson.JSONObject doGetStr(String url) { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); com.alibaba.fastjson.JSONObject jsonObject = null; try { HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if(entity!=null){ String result = EntityUtils.toString(entity,"UTF-8"); jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return jsonObject; } public static com.alibaba.fastjson.JSONObject doPostStr(String url,String outStr) { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); com.alibaba.fastjson.JSONObject jsonObject = null; httpPost.setEntity(new StringEntity(outStr, "UTF-8")); try { HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); if(entity!=null){ String result = EntityUtils.toString(entity, "UTF-8"); jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jsonObject; } /** * * Json-lib:Http請求Get返回JSONObject * @param url 請求的url地址 * @return */ @SuppressWarnings("deprecation") public static JSONObject doGetStr2(String url) { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); JSONObject jsonObject = null; try { HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if(entity!=null){ String result = EntityUtils.toString(entity,"UTF-8"); jsonObject = JSONObject.fromObject(result); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return jsonObject; } /** * 使用json-lib的JSONObject實現HttpClient請求,獲取JSONObject對象 * @param url 請求的url地址 * @param outStr 請求的參數 * @return */ public static JSONObject doPostStr2(String url,String outStr) { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); JSONObject jsonObject = null; httpPost.setEntity(new StringEntity(outStr, "UTF-8")); try { HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); if(entity!=null){ String result = EntityUtils.toString(entity, "UTF-8"); jsonObject = JSONObject.fromObject(result); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return jsonObject; }