Java工具类-HttpUtil

  1 package com.sh.util;
  2 import java.io.IOException;
  3 import java.io.UnsupportedEncodingException;
  4 import java.net.URI;
  5 import java.security.cert.X509Certificate;
  6 import java.util.ArrayList;
  7 import java.util.List;
  8 import java.util.Map;
  9 
 10 import javax.net.ssl.SSLContext;
 11 import javax.net.ssl.TrustManager;
 12 import javax.net.ssl.X509TrustManager;
 13 
 14 import org.apache.http.HttpEntity;
 15 import org.apache.http.HttpResponse;
 16 import org.apache.http.NameValuePair;
 17 import org.apache.http.client.ClientProtocolException;
 18 import org.apache.http.client.HttpClient;
 19 import org.apache.http.client.entity.UrlEncodedFormEntity;
 20 import org.apache.http.client.methods.HttpGet;
 21 import org.apache.http.client.methods.HttpPost;
 22 import org.apache.http.conn.ClientConnectionManager;
 23 import org.apache.http.conn.scheme.Scheme;
 24 import org.apache.http.conn.scheme.SchemeRegistry;
 25 import org.apache.http.conn.ssl.SSLSocketFactory;
 26 import org.apache.http.impl.client.DefaultHttpClient;
 27 import org.apache.http.message.BasicNameValuePair;
 28 import org.apache.http.util.EntityUtils;
 29 public class HttpsUtil {
 30     /**
 31     * 获取可信任https链接,以避免不受信任证书出现peer not authenticated异常
 32     *
 33     * @param base
 34     * @return
 35     */
 36     public static HttpClient wrapClient(HttpClient base) {
 37         try {
 38             SSLContext ctx = SSLContext.getInstance("TLS");
 39             X509TrustManager tm = new X509TrustManager() {
 40             public void checkClientTrusted(X509Certificate[] xcs,String string) {
 41             }
 42             public void checkServerTrusted(X509Certificate[] xcs,String string) {
 43             }
 44             public X509Certificate[] getAcceptedIssuers() {
 45                 return null;
 46             }
 47             };
 48             ctx.init(null, new TrustManager[] { tm }, null);
 49             SSLSocketFactory ssf = new SSLSocketFactory(ctx);
 50             ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
 51             ClientConnectionManager ccm = base.getConnectionManager();
 52             SchemeRegistry sr = ccm.getSchemeRegistry();
 53             sr.register(new Scheme("https", ssf, 443));
 54             return new DefaultHttpClient(ccm, base.getParams());
 55         } catch (Exception ex) {
 56             ex.printStackTrace();
 57         return null;
 58         }
 59     }
 60     
 61     /**
 62      * http get请求
 63      * @param url 请求地址
 64      * @param headers 请求头
 65      * @param pmap 请求参数
 66      * @param ishttps 是否使用https  true:使用 false:不使用
 67      * @return
 68      */
 69     public static String sendHttpsGet(String url,Map<String, String> headers,Map<String, String> pmap,boolean ishttps){
 70         HttpClient client = new DefaultHttpClient(); 
 71         if(ishttps){
 72             client = wrapClient(client);
 73         }
 74         // 实例化HTTP方法
 75         HttpGet get = new HttpGet();
 76         for(String keyh : headers.keySet()) {
 77             get.setHeader(keyh,headers.get(keyh));
 78         }
 79         String params = "";
 80         for(String keyp : pmap.keySet()) {
 81             params += "&" + keyp + "=" + pmap.get(keyp);
 82         }
 83         url += params.replaceAll("^&", "?");
 84         String result ="";
 85         try {
 86             get.setURI(new URI(url));
 87             HttpResponse response = client.execute(get);
 88             result = EntityUtils.toString(response.getEntity());
 89         } catch (Exception e) {
 90             // TODO: handle exception
 91         }
 92         try {
 93             result=new String(result.getBytes("ISO-8859-1"),"utf-8");
 94         } catch (UnsupportedEncodingException e) {
 95             // TODO Auto-generated catch block
 96             e.printStackTrace();
 97         }
 98         return result;
 99         
100     }
101     
102     /**
103      * http post请求
104      * @param url 请求地址
105      * @param headers 请求头
106      * @param pmap 请求参数
107      * @param ishttps 是否使用https  true:使用 false:不使用
108      * @return  HttpEntity  使用org.apache.http.util.EntityUtils.toString()、com.alibaba.fastjson.JSON.parseObject()解析
109      */
110     public static HttpEntity sendHttpsPost(String url,Map<String, String> headers,Map<String, String> pmap,boolean ishttps){
111         HttpClient client = new DefaultHttpClient();
112         if(ishttps){
113             client = wrapClient(client);
114         }
115         HttpPost postrequest = new HttpPost(url);
116         HttpEntity entity = null;
117         try {
118             for(String keyh : headers.keySet()) {
119                 postrequest.setHeader(keyh, headers.get(keyh));
120             }
121             List<NameValuePair> nvps = new ArrayList<NameValuePair>();
122             for(String key : pmap.keySet()) {
123                 nvps.add(new BasicNameValuePair(key,pmap.get(key)));
124             }
125             
126             postrequest.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));
127             HttpResponse execute = client.execute(postrequest);
128             entity = execute.getEntity();
129         } catch (UnsupportedEncodingException e) {
130             e.printStackTrace();
131         } catch (ClientProtocolException e) {
132             e.printStackTrace();
133         } catch (IOException e) {
134             e.printStackTrace();
135         } catch (Exception e) {
136             e.printStackTrace();
137         }
138         return entity;
139     }
140     public static void main(String[] args) {
141         String t="{'uuid':'ec85f716-7647-439b-8d28-34cb21f95098','session':'4d590d61-b3e1-464f-b89a-03b69a90e040','label':null,'type':'pub','permanent':true,'data':null,'time_created':'2017-10-18T02:18:48.910656Z','live_days':15,'expire_in':'2017-11-02T02:18:48.910Z'}";
142          net.sf.json.JSONArray jsonarr = net.sf.json.JSONArray.fromObject(t);
143         for(int i=0;i<jsonarr.size();i++){
144             net.sf.json.JSONObject jsonObject = jsonarr.getJSONObject(i);
145             System.out.println(jsonObject.get("uuid"));
146         }
147         
148     }
149      
150 }
原文地址:https://www.cnblogs.com/rb2010/p/8376855.html