okhttp简介
okhttp是一个封装URL,比HttpClient更友好易用的工具.
特点
1.支持http和https协议,api相同,易用;
2.http使用线程池,https使用多路复用;
3.okhttp支持同步和异步调用;
4.支持普通form和文件上传form;
5.提供了拦截器,操作请求和响应(日志,请求头,body等);
6.okhttp可以设置缓存;
使用
1.创建OkHttpClient对象;
2.设置timeout时间,包括连接超时,读超市,写超时;
3.可选(拦截器);
4.创建RequestBody对象,即请求体;
5.创建Request对象,发送请求;
6.创建Response对象,接受响应内容;
源码链接
链接:http://pan.baidu.com/s/1miJVETa 密码:ldsc
封装的工具类
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* @author lcj
* @version 1.0
* @description okhttp get post工具类
* @Create 2017-06-16
*/
public class OkHttpUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(OkHttpUtil.class);
private static final OkHttpClient CLIENT;
static {
CLIENT = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS) //连接超时
.writeTimeout(10, TimeUnit.SECONDS) //写超时
.readTimeout(30, TimeUnit.SECONDS) //读超时
.build();
}
public enum OkHttpMethod {
POST,
PUT,
DELETE
}
/**
* get请求,支持http和https
* @param url 地址,比如: http://wwww.baidu.com
* @param params 参数,可以为null
* @param headers 请求头,可以为null
* @return
*/
public static String get(String url,Map params,Map headers){
//Builder对象
Request.Builder builder = new Request.Builder();
//处理参数
if(null != params && params.size() > 0){
StringBuilder stringBuilder = new StringBuilder("?");
params.forEach((k,v) -> {
stringBuilder.append(k).append("=").append(v).append("&");
});
String param = stringBuilder.toString();
url += param.substring(0,param.lastIndexOf("&"));
}
//处理请求头
if(null != headers && headers.size() > 0){
headers.forEach((k,v) -> builder.header(k,v));
}
//LOGGER.info("url:{}",url);
Request request = builder.url(url).build();
//LOGGER.info("所有的请求头: ");
//request.headers().toMultimap().forEach((k,v) -> {
// LOGGER.info("{} : {}",k,v);
//});
//创建响应对象
try {
Response response = CLIENT.newCall(request).execute();
if(!response.isSuccessful()){
LOGGER.error("发送get请求失败,状态码:{}",response.code());
return "";
}
return response.body().string();
} catch (IOException e) {
LOGGER.error("发送get请求失败,原因:{}",e.getCause());
return "";
}
}
/**
* post,put,delete请求,支持http和https
* @param url 地址,比如: http://wwww.baidu.com
* @param params 参数,可以为null
* @param headers 请求头,可以为null
* @param okHttpMethod 请求方式
* @return
*/
public static String postOrPutOrDelete(String url,Map params,Map headers,OkHttpMethod okHttpMethod){
//Builder对象
Request.Builder builder = new Request.Builder();
//处理请求头
if(null != headers && headers.size() > 0){
headers.forEach((k,v) -> builder.header(k,v));
}
//处理参数
if(null != params && params.size() > 0){
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(params));
switch (okHttpMethod){
case POST:
builder.post(body);
break;
case PUT:
builder.put(body);
break;
case DELETE:
builder.delete(body);
break;
default:
builder.post(body);
break;
}
}else {
switch (okHttpMethod){
case DELETE:
default:
builder.delete();
break;
}
}
//LOGGER.info("url:{}",url);
Request request = builder.url(url).build();
//LOGGER.info("所有的请求头: ");
//request.headers().toMultimap().forEach((k,v) -> {
// LOGGER.info("{} : {}",k,v);
//});
//创建响应对象
try {
Response response = CLIENT.newCall(request).execute();
if(!response.isSuccessful()){
LOGGER.error("发送请求失败,状态码:{}",response.code());
return "";
}
return response.body().string();
} catch (IOException e) {
LOGGER.error("发送请求失败,原因:{}",e.getCause());
return "";
}
}
public static void main(String[] args) {
String url = "http://wwww.baidu.com";
Map params = Maps.newHashMap();
params.put("title","title");
params.put("age",23);
params.put("sex",true);
Map headers = Maps.newHashMap();
headers.put("User-Agent","Android");
headers.put("Content-Type","application/json");
String result = get(url,params,headers);
System.out.println(result);
}
}