此时情绪此时天,无事小神仙
好好生活,平平淡淡每一天

编辑

Http请求代码模板类

模板方法代码

/**
     * @Title:httpInterface
     * @author:踏步
     * @Description: http访问网络
     * @param url--HTTP请求地址
     * @param paramsMap--请求参数Map
     * @param method--HTTP请求方法:get或者post
     * @param requestHeader--请求头参数Map
     * @return Map<String,Object>
     */
    public static Map<String, Object> httpInterface(String url, Map<String, Object> paramsMap, String method,
        Map<String, String> requestHeader) {
        HttpGet get = null;// get访问
        HttpPost post = null;// post访问
        HttpResponse response = null;// 响应\
        // http结果map
        Map<String, Object> httpMap = new HashMap<String, Object>();
        try {
            httpMap.put("code", "succeed");
            System.out.println("HTTP请求地址: " + url);
            // 创建一个DefaultHttpClient的实例
            DefaultHttpClient client = new DefaultHttpClient();
            if (url.indexOf("HTTPS:") > -1) {
                client = (DefaultHttpClient)WebClientDevWrapper.wrapClient(client);
            }
            // 设置连接超时时间,单位毫秒
            client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
            // 等待结果超时时间,单位毫秒
            client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);
            if (method.equalsIgnoreCase("GET")) {
                // get访问
                get = new HttpGet(url);
                // 请求头参数不为空时,设置请求头
                if (!QwyUtil.isNullAndEmpty(requestHeader)) {
                    for (String key : requestHeader.keySet()) {
                        get.setHeader(key, requestHeader.get(key));
                    }
                }
                response = client.execute(get);
            } else {
                // Post访问;
                post = new HttpPost(url);
                // 请求头参数不为空时,设置请求头
                if (!QwyUtil.isNullAndEmpty(requestHeader)) {
                    for (String key : requestHeader.keySet()) {
                        post.setHeader(key, requestHeader.get(key));
                    }
                }
                // 封装参数
                if (!isNullAndEmpty(paramsMap)) {
                    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
                    Iterator<String> keys = paramsMap.keySet().iterator();
                    while (keys.hasNext()) {
                        String key = keys.next();
                        params.add(new BasicNameValuePair(key, paramsMap.get(key).toString()));
                    }
                    HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
                    post.setEntity(entity);
                }
                response = client.execute(post);
            }
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String str = EntityUtils.toString(response.getEntity(), "UTF-8");
                JSONObject jsonObject = new JSONObject(str);
                return jsonToMap(jsonObject);
            } else {
                httpMap.put("code", "fail");
                httpMap.put("message", "http访问异常:" + response.getStatusLine().toString());
                System.out.println(response.getStatusLine().toString());
            }
        } catch (Exception e) {
            httpMap.put("code", "fail");
            httpMap.put("message", "http访问异常!");
            e.printStackTrace();
            System.out.println(e.getMessage());
        } finally {
            return httpMap;
        }
    }

    /**
     * @Title:jsonToMap
     * @author:踏步
     * @Description: 将json转换成Map格式;
     * @param json--JSONObject
     * @return Map<String,Object>
     */
    public static Map<String, Object> jsonToMap(JSONObject json) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            if (!isNullAndEmpty(json)) {
                Iterator<String> iterator = json.keys();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    map.put(key, json.get(key));
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return map;
    }

模板方法代码>必须依赖代码

import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

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


/**
 * 避免HttpClient的”SSLPeerUnverifiedException: peer not authenticated”异常
 * 不用导入SSL证书
 * @author shipengzhi(shipengzhi@sogou-inc.com)
 *
 */
public  class WebClientDevWrapper {

    public static org.apache.http.client.HttpClient wrapClient(org.apache.http.client.HttpClient base) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
                public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
            };
            ctx.init(null, new TrustManager[] { tm }, null);

            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
            registry.register(new Scheme("https", new EasySSLSocketFactory(), 9543));
            ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(base.getParams(),registry);
            return new DefaultHttpClient(mgr, base.getParams());
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
}

posted @ 2019-12-30 14:41  踏步  阅读(1012)  评论(0编辑  收藏  举报