之前一直用的是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();
}
2018-20-29修改,添加文件下载方法(主要是下载图片)
package com.gwc.util;
import okhttp3.*;
import okhttp3.Request.Builder;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* OkHttp工具类
*
* @author chenggaowei Created on 2018-05-08 13:04
**/
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(60, TimeUnit.SECONDS) //连接超时
.writeTimeout(60, TimeUnit.SECONDS) //写超时
.readTimeout(60, TimeUnit.SECONDS) //读超时
.build();
}
/**
* get请求,参数一般都在url里
*
* @param url 请求地址
*/
public static String sendGet(String url) throws IOException {
return sendGet(url, null);
}
/**
* get请求
*
* @param url 请求地址
* @param headers 请求头
* @return
* @throws IOException
*/
public static String sendGet(String url, Map<String, Object> headers) throws IOException {
Request request = getBuilder(url, headers).build();
Response response = CLIENT.newCall(request).execute();
return response.body().string();
}
/**
* post 提交json
*
* @param url 请求地址
* @param jsonStr json字符串
* @return
* @throws IOException
*/
public static String sendPostJson(String url, String jsonStr) throws IOException {
return sendPostJson(url, null, jsonStr);
}
/**
* post 提交json
*
* @param url 请求地址
* @param headers 请求头
* @param jsonStr json字符串
* @return
* @throws IOException
*/
public static String sendPostJson(String url, Map<?, ?> headers, String jsonStr) throws IOException {
RequestBody body = RequestBody.create(JSON_TYPE, jsonStr);
Request request = getBuilder(url, headers).post(body).build();
Response response = CLIENT.newCall(request).execute();
return response.body().string();
}
/**
* post提交表单
*
* @param url 请求地址
* @param params 参数
* @return
* @throws IOException
*/
public static String sendPost(String url, Map<?, ?> params)
throws IOException {
return sendPost(url, null, params, null);
}
/**
* post提交表单
*
* @param url 请求地址
* @param params 参数
* @param files 文件
* @return
* @throws IOException
*/
public static String sendPost(String url, Map<?, ?> params, List<MultipartFile> files)
throws IOException {
return sendPost(url, null, params, files);
}
/**
* post 提交表单
*
* @param url 请求地址
* @param headers 请求头
* @param params 参数
* @param files 文件
* @return
* @throws IOException
*/
public static String sendPost(String url, Map<?, ?> headers, Map<?, ?> params, List<MultipartFile> files)
throws IOException {
if (CollectionUtils.isEmpty(files)) { // 没有文件上传的
FormBody.Builder requestBody = new FormBody.Builder();
if (MapUtils.isNotEmpty(params)) {
params.forEach((k, v) -> requestBody.add(k.toString(), 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.toString(), v.toString()));
}
if (CollectionUtils.isNotEmpty(files)) {
for (MultipartFile file : files) {
if (null != file) {
byte[] bytes = new byte[file.getInputStream().available()];
file.getInputStream().read(bytes);
RequestBody body = RequestBody.create(MediaType.parse(file.getContentType()), bytes);
requestBody.addFormDataPart(file.getName(), file.getOriginalFilename(), body);
}
}
}
Request request = getBuilder(url, headers).post(requestBody.build()).build();
Response response = CLIENT.newCall(request).execute();
return response.body().string();
}
}
/**
* 根据url下载图片到本地,这里不校验图片路径的正确与否
*
* @param url
* @return
* @throws IOException
*/
public static File downloadImage(String url) throws Exception {
String ext = FilenameUtils.getExtension(url);
if (StringUtils.isEmpty(ext)) {
ext = "png";
}
String regex = "\\.[a-zA-Z]+$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher("." + ext);
if (!matcher.find()) {
ext = "png";
}
String pathname = FileUtil.getTempPath() + File.separator + System.currentTimeMillis() + "." + ext;
File file = new File(pathname);
Request request = new Request.Builder().url(url).build();
Call call = CLIENT.newCall(request);
Response response = call.execute();
byte[] buf = new byte[2048];
int len;
InputStream inputStream = response.body().byteStream();
FileOutputStream fileOutputStream = new FileOutputStream(file);
while ((len = inputStream.read(buf)) != -1) {
fileOutputStream.write(buf, 0, len);
}
fileOutputStream.flush();
return file;
}
private static Builder getBuilder(String url, Map<?, ?> headers) {
Request.Builder builder = new Request.Builder().url(url);
if (MapUtils.isNotEmpty(headers)) {
headers.forEach((k, v) -> builder.addHeader(k.toString(), v.toString()));
}
return builder;
}
public static void main(String[] args) throws Exception {
String url = "http://cj.jj20.com/d/cj0.php?p=/up/allimg/1111/10141Q22930/1Q014122930-1.jpg&w=1536&h=864";
// String url = "123";
System.out.println(downloadImage(url).getAbsolutePath());
}
}