zoukankan      html  css  js  c++  java
  • Http请求代码模板——Android

     依赖最下面的方法:

       /**
         * http访问网络
         * @param url HTTP请求地址
         * @param paramsMap 请求参数Map
         * @param method HTTP请求方法:get或者post
         * @param requestHeader 请求头参数Map
         * @return
         */
        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");
                Log.i(TAG, "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());
                    Log.e(TAG, response.getStatusLine().toString());
                }
            } catch (Exception e) {
                httpMap.put("code", "fail");
                httpMap.put("message", "http访问异常!");
                e.printStackTrace();
                Log.e(TAG, "" + e.getMessage());
            } finally {
                return httpMap;
            }
        }
    
        /**
         * 将json转换成Map格式;
         * @param json JSONObject
         * @return
         */
        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();
                Log.e(TAG, 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;
            }
        }
    }
  • 相关阅读:
    无线Mesh网络技术基础与应用
    BLE低功耗蓝牙关键技术解析与应用
    Android Studio NDK开发入门
    Android 注解的使用与注意事项
    图形图像处理库大全
    vs2010下C++调用lib或dll文件
    网线连接电脑共享文件传递
    分配和释放 BSTR 的内存
    #include <objsafe.h>//OCX控件在IE8浏览器下不能使用问题
    彻底搞定char/wchar_t/unicode
  • 原文地址:https://www.cnblogs.com/mjtabu/p/12119590.html
Copyright © 2011-2022 走看看