OkHTTPClient

Posted 灬小乙

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
        String finalUrl = null;
        if("M".equals(type)) {
            finalUrl = JD_M_HOST+url;
        }else if("V".equals(type)) {
            finalUrl = JD_V_HOST+url;
        }else {
            log.error("TYPE类型只能为M或者V!");
        }
         if (token == true) {
             finalUrl = url;
        }
        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 {
                  //请求失败
                String content = "【出现返回异常的接口】:"+finalUrl + " 【返回HTTP CODE】:"+response.message() + "  【请求的数据】: "+JSON.toJSONString(params);
                shopTools.sendErrorMail("京东实物接口服务器异常返回", content, null);
                if(JDCommonConstant.SUBMIT_ORDER.equals(url) || JDCommonConstant.ORDER_PAY.equals(url)) {
                    //如果是下单或者支付接口
                    JSONObject orderFail = new JSONObject();
                    orderFail.put("responseFail", "responseFail");
                    return orderFail;
                }
              log.info("请求失败,返回信息: "+response.message());
              return null;
            }            
        } catch (IOException e) {
            log.info("IOException!!!!!!!"+e.getMessage());
            String content = "【出现IO异常的接口】:"+finalUrl + " 【异常原因】:"+e.getMessage()+ "  【请求的数据】: "+JSON.toJSONString(params);
            shopTools.sendErrorMail("调用京东实物接口出现IO异常", content, null);
             if(JDCommonConstant.SUBMIT_ORDER.equals(url) || JDCommonConstant.ORDER_PAY.equals(url)) {
                  //如果是下单或者支付接口
                  JSONObject orderFail = new JSONObject();
                  orderFail.put("IOException", "IOException");
                  return orderFail;
           }
            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

以上是关于OkHTTPClient的主要内容,如果未能解决你的问题,请参考以下文章

android OkHttpClient 请求错误

OkHttpOkHttp 源码分析 ( OkHttpClient.Builder 构造器源码分析 )

OkHttpClient 关闭连接

Android Studio OkHttpClient使用

如何使用 okHttpClient 执行 graphql 查询?

如何创建符合 GRPC 的 OkHttpClient?