OkHTTPClient

2018-06-18 02:02:23来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

一,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

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Java修行之路

下一篇:java并发编程艺术