github地址
https://github.com/square/okhttp
参考地址 https://square.github.io/okhttp/recipes/
常规使用
- 引用Maven依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.0.1</version>
</dependency>
- Spring
定义bean
public final static int CONNECT_TIMEOUT =60;
public final static int READ_TIMEOUT=100;
public final static int WRITE_TIMEOUT=60;
@Bean
public OkHttpClient okHttpClient(){
OkHttpClient client = (new OkHttpClient()).newBuilder().readTimeout(READ_TIMEOUT,TimeUnit.SECONDS).connectTimeout(CONNECT_TIMEOUT,TimeUnit.SECONDS).writeTimeout(WRITE_TIMEOUT,TimeUnit.SECONDS).connectionPool(new ConnectionPool(20, 40L, TimeUnit.MINUTES)).build();
return client;
}
post
- postJson请求
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, JSONUtils.toJson(jsonMap));
-postform表单请求
RequestBody body= new FormBody.Builder().add(name, value).build();
-post文件上传
RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
MultipartBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("filename", "xxx.png", requestBody)
.build();
Request.Builder builder = new Request.Builder();
Request request = builder
.url(url)
.post(body)
.build();
Call call = okHttpClient.newCall(request);
Response response = call.execute();
response.body().string();
个人常使用就是这3中,相比较Post请求,get请求所需要的参数更少
Get请求
Request request = new Request.Builder()
.url(url)
.build();
Call call = okHttpClient.newCall(request);
Response response = call.execute();
response.body().string();
因为我不是很常使用异步的请求,对于Okhttp异步用法不甚了解,大部份业务都可以用同步去处理,就没仔细研究异步。
header vs addHeader
替换当前header中的值,公共的参数直接用这个替换
builder.header("键", “值”);
不会替换当前header中的值,只会累加,一般是有额外的参数,会单独处理
builder.addHeader("键", “值”);