简介:
HTTP是现代应用常用的一种交换数据和媒体的网络方式,高效地使用HTTP能让资源加载更快,节省带宽。OkHttp是一个高效的HTTP客户端,它有以下默认特性:
- 支持HTTP/2,允许所有同一个主机地址的请求共享同一个socket连接
- 连接池减少请求延时
- 透明的GZIP压缩减少响应数据的大小
- 缓存响应内容,避免一些完全重复的请求
代码:
import net.sf.jmimemagic.*;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static java.lang.String.valueOf;
@Slf4j
public class OkHttpUtils {
private static final String CHARSET_NAME = "UTF-8";
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build();
public static Map<String, String> getToken(HttpServletRequest request) {
Map<String, String> token = new HashMap<>();
javax.servlet.http.Cookie cookies[] = request.getCookies();
String cloudSsoToken = "";
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("cloud-sso-token".equals(cookie.getName()))
cloudSsoToken = "Bearer " + cookie.getValue();
}
log.debug("从cookie获取token: {}", cloudSsoToken);
}
// cookie没有则尝试重header取
if (StringUtils.isEmpty(cloudSsoToken)) {
cloudSsoToken = request.getHeader("Authorization");
log.debug("从header获取token: {}", cloudSsoToken);
}
if (cloudSsoToken == null) {
cloudSsoToken = "";
}
token.put("Authorization", cloudSsoToken);
return token;
}
/**
* 同步get
*
* @param url
* @return
* @throws Exception
*/
public static String get(String url) throws Exception {
Request request = new Request.Builder().url(url).build();
Response response = execute(request);
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
/**
* 同步get
*
* @param url
* @param token
* @return
* @throws Exception
*/
public static String getByToken(String url, Map<String, String> token) throws Exception {
String v = token.get("Authorization");
if (v == null) {
v = "";
}
Request request = new Request.Builder().url(url).addHeader("Authorization", v).build();
Response response = execute(request);
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
/**
* 同步get请求
*
* @param url
* @param data
* @return
* @throws Exception
*/
public static String get(String url, Map<String, Object> data) throws Exception {
url = getRequestUrl(url, data);
Request request = new Request.Builder().url(url).build();
Response response = execute(request);
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
/**
* 同步get请求
*
* @param url
* @param data
* @param token
* @return
* @throws Exception
*/
public static String getByToken(String url, Map<String, Object> data, Map<String, String> token) throws Exception {
url = getRequestUrl(url, data);
Request request = new Request.Builder().url(url).addHeader("Authorization", token.get("Authorization")).build();
Response response = execute(request);
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
/**
* 异步get请求
*
* @param url
* @param responseCallback
* @return
* @throws Exception
*/
public static void get(String url, Callback responseCallback) throws Exception {
Request request = new Request.Builder().url(url).build();
enqueue(request, responseCallback);
}
/**
* 异步get
*
* @param url
* @param data
* @param responseCallback
* @return
* @throws Exception
*/
public static void get(String url, Map<String, Object> data, Callback responseCallback) throws Exception {
url = getRequestUrl(url, data);
Request request = new Request.Builder().url(url).build();
enqueue(request, responseCallback);
}
/**
* 同步post json数据
*
* @param url
* @param json
* @return
* @throws IOException
*/
public static String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder().url(url).post(body).build();
Response response = execute(request);
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
/**
* 同步post提交表单数据(包含文件)
*
* @param url
* @param params
* @return
* @throws IOException
*/
public static String post(String url, Map<String, Object> params) throws IOException, MagicParseException, MagicException, MagicMatchNotFoundException {
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
Object obj = entry.getValue();
if (obj instanceof File[]) {
File[] files = (File[]) obj;
for (File file : files) {
MagicMatch match = Magic.getMagicMatch(file, false, true);
RequestBody body = RequestBody.create(MediaType.parse(match.getMimeType()), file);
builder.addFormDataPart(entry.getKey(), file.getName(), body);
}
} else {
builder.addFormDataPart(valueOf(entry.getKey()), valueOf(entry.getValue()));
}
}
}
Request request = new Request.Builder()
.url(url)
.post(builder.build())
.build();
Response response = execute(request);
return response.body().string();
}
/**
* 异步post json
*
* @param url
* @param json
* @param responseCallback
* @throws IOException
*/
public static void post(String url, String json, Callback responseCallback) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder().url(url).post(body).build();
enqueue(request, responseCallback);
}
/**
* 异步post提交表单数据(包含文件)
*
* @param url
* @param params
* @param responseCallback
* @throws IOException
*/
public static void post(String url, Map<String, Object> params, Callback responseCallback) throws MagicParseException, MagicException, MagicMatchNotFoundException {
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
Object obj = entry.getValue();
if (obj instanceof File[]) {
File[] files = (File[]) obj;
for (File file : files) {
MagicMatch match = Magic.getMagicMatch(file, false, true);
RequestBody body = RequestBody.create(MediaType.parse(match.getMimeType()), file);
builder.addFormDataPart(entry.getKey(), file.getName(), body);
}
} else {
builder.addFormDataPart(valueOf(entry.getKey()), valueOf(entry.getValue()));
}
}
}
Request request = new Request.Builder()
.url(url)
.post(builder.build())
.build();
enqueue(request, responseCallback);
}
/**
* 同步put
*
* @param url
* @param json
* @return
* @throws IOException
*/
public static String put(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder().url(url).put(body).build();
Response response = execute(request);
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
/**
* 同步put key-value
*
* @param url
* @param data
* @return
* @throws IOException
*/
public static String put(String url, Map<String, String> data) throws IOException {
FormBody.Builder formBuilder = new FormBody.Builder();
for (Map.Entry<String, String> item : data.entrySet()) {
formBuilder.add(item.getKey(), item.getValue());
}
RequestBody body = formBuilder.build();
Request request = new Request.Builder().url(url).put(body).build();
Response response = execute(request);
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
/**
* 异步put json
*
* @param url
* @param json
* @throws IOException
*/
public static void put(String url, String json, Callback responseCallback) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder().url(url).put(body).build();
enqueue(request, responseCallback);
}
/**
* 异步put key-value
*
* @param url
* @param data
* @param responseCallback
* @throws IOException
*/
public static void put(String url, Map<String, String> data, Callback responseCallback) throws IOException {
FormBody.Builder formBuilder = new FormBody.Builder();
for (Map.Entry<String, String> item : data.entrySet()) {
formBuilder.add(item.getKey(), item.getValue());
}
RequestBody body = formBuilder.build();
Request request = new Request.Builder().url(url).put(body).build();
enqueue(request, responseCallback);
}
/**
* 通用同步请求。
*
* @param request
* @return
* @throws IOException
*/
public static Response execute(Request request) throws IOException {
return okHttpClient.newCall(request).execute();
}
/**
* 通用异步请求
*
* @param request
* @param responseCallback
*/
public static void enqueue(Request request, Callback responseCallback) {
okHttpClient.newCall(request).enqueue(responseCallback);
}
/**
* 开启异步线程访问网络, 且不在意返回结果(实现空callback)
*
* @param request
*/
public static void enqueue(Request request) {
okHttpClient.newCall(request).enqueue(new Callback() {
public void onFailure(Call call, IOException e) {
// TODO Auto-generated method stub
}
public void onResponse(Call call, Response response) throws IOException {
// TODO Auto-generated method stub
}
});
}
public static String getStringFromServer(String url) throws IOException {
Request request = new Request.Builder().url(url).build();
Response response = execute(request);
if (response.isSuccessful()) {
String responseUrl = response.body().string();
return responseUrl;
} else {
throw new IOException("Unexpected code " + response);
}
}
/**
* 为HttpGet 的 url 方便的添加1个name value 参数。
*
* @param url
* @param name
* @param value
* @return
*/
public static String attachHttpGetParam(String url, String name, String value) {
return url + "?" + name + "=" + value;
}
/**
* get方式URL拼接
*
* @param url
* @param map
* @return
*/
private static String getRequestUrl(String url, Map<String, Object> map) {
if (map == null || map.size() == 0) {
return url;
} else {
StringBuilder newUrl = new StringBuilder(url);
if (url.indexOf("?") == -1) {
newUrl.append("?rd=" + Math.random());
}
for (Map.Entry<String, Object> item : map.entrySet()) {
if (false == item.getKey().trim().isEmpty()) {
try {
newUrl.append("&" + item.getKey().trim() + "="
+ URLEncoder.encode(valueOf(item.getValue()).trim(), "GBK"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
return newUrl.toString();
}
}
}