apache http client 与 okhttp 使用

apache http升级经常做不兼容修改,这个使用起来有点蛋疼
okhttp升级到3.0以后与2.X版本也是做了不兼容修改,有点蛋疼

apache httpClient组件由于用的比较早,自己有比较好的封装使用起来也很简单; apache httpClient 对Cooke已经有很好的处理,访问同一个网站的URL,可以进行很好的Cookie传递;apache对返回Response流也进行了很好的预处理,比如gzip流的解压。

okhttp使用优点

okhttp 的api使用起来就,就像在进行http对话,创建一个httpClient后提供request,后处理response,代码层级清晰理解简单;okhttp对cookie管理还需要自己使实现;response的gzip需自己解压; 


okhttp3变化

com.squareup.okhttp.* 改成了 okhttp3
okhttp3 增加Builder类 
比如OkHttpClient MultipartBuilder 被替换成 FormBody.Builder 使用起来更加方便
FormEncodingBuilder 被替换成 FormBody.Builder 使用起来更加方便
Cookie处理方式有修改


okhttp 初始化变更

OkHttpClient client = new OkHttpClient();
client.setReadTimeout(10, TimeUnit.SECONDS);
client.setConnectTimeout(10, TimeUnit.SECONDS);
client.setFollowRedirects(true);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.readTimeout(10, TimeUnit.SECONDS);
builder.connectTimeout(10, TimeUnit.SECONDS);
builder.followRedirects(true);
return builder.build();


FormEncodingBuilder 被替换成 FormBody.Builder 使用起来更加方便

//已经删除
FormEncodingBuilder builder = new FormEncodingBuilder();
for (MucangNameValuePair pair : list) {
    builder.add(pair.getName(), pair.getValue());
}
FormBody.Builder builder = new FormBody.Builder();
for (MucangNameValuePair pair : list) {
    builder.add(pair.getName(), pair.getValue());
}


Cookie处理方式有修改

cookie okhttp2 

client.setCookieHandler(new CookieHandler() {
            @Override
            public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException {
                return null;
            }

            @Override
            public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {

            }
        });

cookie okhttp3

builder.cookieJar(new CookieJar() {
    @Override
    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
        
    }

    @Override
    public List<Cookie> loadForRequest(HttpUrl url) {
        return null;
    }
})


//可以对 Method 与 HttpRequestBase再做简单的封装就可以处理任意类型的请求 如:put、delete
public static String httpPost(String url, HttpEntity entity, List<Header> headers) {
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(80000)
            .setSocketTimeout(80000)
            .build();
    try (CloseableHttpClient httpClient = HttpClientBuilder
            .create()
            .setDefaultRequestConfig(requestConfig)
            .build()) {
        HttpPost httpPost = new HttpPost(url);
        if (CollectionUtils.isNotEmpty(headers)) {
            for (Header header : headers) {
                httpPost.addHeader(header);
            }
        }
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost);
        return EntityUtils.toString(response.getEntity(), "UTF-8");
    } catch (Exception ex) {
        LOG.error(null, ex);
    }
    return null;
}


public static <T extends Object> T httpGet(String url, List<Header> headers, ResponseHandler handler) {
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(8000)
            .setSocketTimeout(8000)
            .build();
    try (CloseableHttpClient httpClient = HttpClientBuilder
            .create()
            .setDefaultRequestConfig(requestConfig)
            .build()) {
        HttpGet httpGet = new HttpGet(url);
        if (CollectionUtils.isNotEmpty(headers)) {
            for (Header header : headers) {
                httpGet.addHeader(header);
            }
        }
        HttpResponse response = httpClient.execute(httpGet);
        return handler.handler(response);
    } catch (Exception ex) {
        LOG.error(null, ex);
    }
    return null;
}

public static interface ResponseHandler {

    <T extends Object> T handler(HttpResponse response) throws Exception;
}

apache 官方文档: http://hc.apache.org/

okhttp 官方文档: http://square.github.io/okhttp/#overview



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值