okhttp简单封装
程序员文章站
2022-07-13 10:58:42
...
之前一直用的是httpclient,今天okhttp简单封装了一下,主要有三个方法
- 发送get请求
- 发送post请求,请求体是json字符串
- 发送post请求,可以什么都不传,可以是简单的表单提交,也可以是带文件上传的表单提交
post上传文件需要的实体
/**
* form表单提交文件上传的文件对象
*
* @author chenggaowei Created on 2018-05-09 23:30
**/
@Getter
@Setter
@ToString
public class PostFile {
/**
* 要上传的文件
*/
private File file;
/**
* 表单对应的名称
*/
private String formName;
public PostFile(File file, String formName) {
this.file = file;
this.formName = formName;
}
}
封装的工具类
/**
* OkHttp工具类
*
* @author chenggaowei Created on 2018-05-09 23:45
**/
public class OkHttpUtil {
private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36";
private static final OkHttpClient CLIENT;
static {
CLIENT = new OkHttpClient.Builder().addInterceptor(chain -> {
Request request = chain.request().newBuilder()
.addHeader("User-Agent", USER_AGENT)
.addHeader("Connection", "keep-alive")
.addHeader("Accept", "*/*")
.build();
return chain.proceed(request);
})
.connectTimeout(5, TimeUnit.SECONDS) //连接超时
.writeTimeout(10, TimeUnit.SECONDS) //写超时
.readTimeout(10, TimeUnit.SECONDS) //读超时
.build();
}
/**
* get请求,参数一般都在url里
*/
public static String sendGet(String url) throws IOException {
Request request = new Request.Builder().url(url).build();
Response response = CLIENT.newCall(request).execute();
return response.body().string();
}
/**
* post提交json
*
* @param url 地址
* @param jsonStr json字符串
*/
public static String sendPost(String url, String jsonStr) throws IOException {
RequestBody body = RequestBody.create(JSON_TYPE, jsonStr);
Request request = new Request.Builder().url(url).post(body).build();
Response response = CLIENT.newCall(request).execute();
return response.body().string();
}
/**
* post提交表单
*
* @param url 地址
* @param params 参数
* @param files 文件
*/
public static String sendPost(String url, Map<String, Object> params, List<PostFile> files)
throws IOException {
if (CollectionUtils.isEmpty(files)) { // 没有文件上传的
FormBody.Builder requestBody = new FormBody.Builder();
if (MapUtils.isNotEmpty(params)) {
params.forEach((k, v) -> requestBody.add(k, v.toString()));
}
FormBody body = requestBody.build();
Request request = new Request.Builder().url(url).post(body).build();
Response response = CLIENT.newCall(request).execute();
return response.body().string();
} else { // 有文件上传的
MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
if (MapUtils.isNotEmpty(params)) {
params.forEach((k, v) -> requestBody.addFormDataPart(k, v.toString()));
}
if (CollectionUtils.isNotEmpty(files)) {
for (PostFile postFile : files) {
if (null != postFile.getFile()) {
Path path = Paths.get(postFile.getFile().getName());
String contentType = Files.probeContentType(path);
if (StringUtils.isEmpty(contentType)) {
contentType = "application/octet-stream";
}
RequestBody body = RequestBody.create(MediaType.parse(contentType), postFile.getFile());
requestBody.addFormDataPart(postFile.getFormName(), postFile.getFile().getName(), body);
}
}
}
Request request = new Request.Builder().url(url).post(requestBody.build()).build();
Response response = CLIENT.newCall(request).execute();
return response.body().string();
}
}
}
如果需要在请求头携带参数类似自定义Header这种,这个时候需要把Builder封装一下
这个也可以封装成类似于PostFile这种数组
private static Builder getBuilder(String url, String header) {
Builder builder = new Builder().url(url);
if (StringUtils.isNotEmpty(token)) {
builder.addHeader("header", header);
}
return builder;
}
调用的地方以get和post为例
/**
* get请求,参数一般都在url里
*/
public static String sendGet(String url, String header) throws IOException {
Request request = getBuilder(url, header).build();
Response response = CLIENT.newCall(request).execute();
return response.body().string();
}
/**
* post提交json
*
* @param url 地址
* @param jsonStr json字符串
*/
public static String sendPost(String url, String header, String jsonStr) throws IOException {
RequestBody body = RequestBody.create(JSON_TYPE, jsonStr);
Request request = getBuilder(url, header).post(body).build();
Response response = CLIENT.newCall(request).execute();
return response.body().string();
}
上一篇: 使用OkHttp拦截器,添加统一参数
下一篇: OkHttp 源码分析