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

转载于:https://www.cnblogs.com/soul-wonder/p/8868505.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值