OkHTTPClient

一,OKHttp介绍

okhttp是一个第三方类库,用于android中请求网络。

这是一个开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献(该公司还贡献了Picasso和LeakCanary) 。用于替代HttpUrlConnection和Apache HttpClient(android API23 里已移除HttpClient)。

okhttp有自己的官网,官网网址:OKHttp官网

如果想了解原码可以在github上下载,地址是:https://github.com/square/okhttp

在AndroidStudio、gradle中使用不需要下载jar包,直接添加依赖即可: 
compile ‘com.squareup.okhttp3:okhttp:3.4.1’

项目中遇到的问题:

    public  JSONObject doPost(String url, JSONObject params,Boolean token,String type) { 
        
        OkHttpClient okHttpClient = new OkHttpClient.Builder()  
                .connectTimeout(JDCommonConstant.TIME_OUT, TimeUnit.SECONDS)  
                .readTimeout(JDCommonConstant.TIME_OUT, TimeUnit.SECONDS)  
                .build();

         Set<String> iterator = null;
         MultipartBody.Builder builder  = new MultipartBody.Builder();
         builder.setType(MultipartBody.FORM);
         if(params != null) {
             iterator = params.keySet();
             for (String str : iterator) {
//                    log.info("当前参数::"+ str + " 类型:" +  params.get(str).getClass());
                    String value = params.getString(str);
                    value=value.startsWith("\"")?value.substring(1,value.length()-1):value;
                    value=value.endsWith("\"")?value.substring(0,value.length()-1):value;
                    value=StringEscapeUtils.unescapeJava(value);
//                    log.info("当前参数的值::"+value +" 长度:"+ value.length());
                      builder.addFormDataPart(str, value);
             }
         }else {
             builder.addFormDataPart("token", ""); 
         }
        RequestBody body = builder.build();
        Request request = new Request.Builder()
            .url(finalUrl)
            .post(body)
            .build();

        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            if(response.isSuccessful()) {
                    String str = response.body().string();
                 str=str.startsWith("\"")?str.substring(1,str.length()-1):str;
                str=str.endsWith("\"")?str.substring(0,str.length()-1):str;
                JSONObject object = JSON.parseObject(str);
                log.info("接口返回值:"+ JSON.toJSONString(object));
                return object; 
            }else {
              //请求失败return null;
            }            
        } catch (IOException e) {return null;
        }
    }

  结果:无法访问,报错

  解决:由于公司是内网,需要设置代理,增加代理

     int proxyPort = 端口号8080;
        String proxyHost = "代理host";
        final String username = "";
        final String password = "";
        Authenticator proxyAuthenticator = new Authenticator() {
              @Override public Request authenticate(Route route, Response response) throws IOException {
                   String credential = Credentials.basic(username, password);
                   return response.request().newBuilder()
                       .header("Proxy-Authorization", credential)
                       .build();
              }

            };
        
        OkHttpClient okHttpClient = new OkHttpClient.Builder()  
                .connectTimeout(JDCommonConstant.TIME_OUT, TimeUnit.SECONDS)  
                .readTimeout(JDCommonConstant.TIME_OUT, TimeUnit.SECONDS)  
                .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)))
                .proxyAuthenticator(proxyAuthenticator)
                .build();

okhttp的使用详细介绍:https://blog.csdn.net/larryqingping/article/details/79440665

posted @ 2018-04-17 18:10  灬小乙  阅读(1199)  评论(0编辑  收藏  举报