基于OkHttp⽹络通信⼯具类(发送get、post请求、⽂件上传
和下载)
⼀、为什么要⽤OkHttp?
okhttp是专注于提升⽹络连接效率的http客户端。
优点:
1、它能实现同⼀ip和端⼝的请求重⽤⼀个socket,这种⽅式能⼤⼤降低⽹络连接的时间,和每次请求都建⽴socket,再断开socket的⽅式相⽐,降低了服务器服务器的压⼒。
2、okhttp 对http和https都有良好的⽀持。
3、okhttp 不⽤担⼼android版本变换的困扰。
4、成熟的⽹络请求解决⽅案,⽐HttpURLConnection更好⽤。
5、⽀持异步发送⽹络请求,响应可在线程处理。
⼆、其它的⽹络通信框架:
1、HttpURLConnection:java.util包下的http客户端,对⽹络请求的封装没有HttpClient那么彻底,api使⽤起来⽐较简单,易于扩展。
2、HttpClient:Apache的⼀个第三⽅⽹络框架,api众多,⽤起来⽐较⽅便,实现⽐较稳定,但不易于扩展。
3、Volley:google推出的⽹络通信框架,适合处理数据量⼩、通信频繁的⽹络操作,内部封装了异步线程,不适合⼤数据量的请求。
下⾯对OkHttp做了⼀个简单的封装,可⽤于发送get、post请求(⽀持请求参数格式为键值对、json格式)、⽂件上传、⽂件下载。
package com.universe.thirdparty.okhttp;
import java.io.IOException;
import java.nio.charset.Charset;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import org.apachemons.lang3.builder.ToStringBuilder;
import org.apachemons.lang3.builder.ToStringStyle;
import com.alibaba.fastjson.JSONObject;
import com.universe.thirdparty.fastjson.CollectionUtils;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.OkHttpClient.Builder;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class OkHttpUtils {
public static final MediaType JSON = ("application/json;charset=utf-8");
public static final MediaType OCTET_STREAM = ("application/octet-stream");
/**
* 超时、读、写时长
*/
private static final long TIMEOUT_MILLIS = 2000;
private static final Builder DEFAULT_CLIENT_BUILDER = new OkHttpClient.Builder();
static {
DEFAULT_adTimeout(Duration.ofMillis(TIMEOUT_MILLIS));
DEFAULT_CLIENT_BUILDER.writeTimeout(Duration.ofMillis(TIMEOUT_MILLIS));
DEFAULT_tTimeout(Duration.ofMillis(TIMEOUT_MILLIS));
}
public static OkHttpClient getOkHttpClient() {
return DEFAULT_CLIENT_BUILDER.build();
}
public static synchronized OkHttpClient getOkHttpClient(long timeoutInMillis) {
DEFAULT_adTimeout(Duration.ofMillis(timeoutInMillis));
DEFAULT_CLIENT_BUILDER.writeTimeout(Duration.ofMillis(timeoutInMillis));
DEFAULT_tTimeout(Duration.ofMillis(timeoutInMillis));
return DEFAULT_CLIENT_BUILDER.build();
}
public static OkHttpResp sendGet(String url, Map<String, Object> reqHeaders, Map<String, Object> params) throws IOException {
return sendGet(url, reqHeaders, params, TIMEOUT_MILLIS);
}
public static OkHttpResp sendGet(String url, Map<String, Object> reqHeaders, Map<String, Object> params, long timeoutInMillis)
throws IOException {
OkHttpClient client = getOkHttpClient(timeoutInMillis);
HttpUrl.Builder urlBuilder = (url).newBuilder();
// 拼接参数
if (!CollectionUtils.isEmpty(params)) {
params.forEach((key, value) -> {
urlBuilder.addEncodedQueryParameter(key, String.valueOf(value));
});
}
HttpUrl httpUrl = urlBuilder.build();
Request.Builder reqBuilder = new Request.Builder().url(httpUrl);
addHeaders(reqHeaders, reqBuilder);
Request request = ().build();
return getResponse(client, request);
}
public static OkHttpResp sendPostInHtmlForm(String url, Map<String, Object> headers, Map<String, Object> params) throws IOException {    return sendPostInHtmlForm(url, headers, params, TIMEOUT_MILLIS);
}
public static OkHttpResp sendPostInHtmlForm(String url, Map<String, Object> reqHeaders, Map<String, Object> params, long timeoutInMillis)      throws IOException {
OkHttpClient client = getOkHttpClient(timeoutInMillis);
Request.Builder reqBuilder = new Request.Builder().url(url);
addHeaders(reqHeaders, reqBuilder);
FormBody.Builder formBuilder = new FormBody.Builder(Charset.forName("UTF-8"));
FormBody formBody = formBuilder.build();
if (!CollectionUtils.isEmpty(params)) {
params.forEach((paramName, paramValue) -> {
formBuilder.add(paramName, String.valueOf(paramValue));
formBuilder.add(paramName, String.valueOf(paramValue));
});
}
Request request = reqBuilder.post(formBody).build();
return getResponse(client, request);
}
public static OkHttpResp sendPostInJsonFormat(String url, Map<String, Object> reqHeaders, Map<String, Object> params) throws IOException {    return sendPostInJsonFormat(url, reqHeaders, params, TIMEOUT_MILLIS);
}
public static OkHttpResp sendPostInJsonFormat(String url, Map<String, Object> reqHeaders, Map<String, Object> params,
long timeoutInMillis) throws IOException {
OkHttpClient client = getOkHttpClient(timeoutInMillis);
Request.Builder reqBuilder = new Request.Builder().url(url);
addHeaders(reqHeaders, reqBuilder);
RequestBody requestBody = ate(JSON, JSONString(params));
Request request = reqBuilder.post(requestBody).build();
return getResponse(client, request);
}
public static OkHttpResp uploadFile(String url, List<MultipartFile> files) throws IOException {
return uploadFile(url, files, TIMEOUT_MILLIS);
}
public static OkHttpResp uploadFile(String url, List<MultipartFile> files, long timeoutInMillis) throws IOException {
OkHttpClient client = getOkHttpClient(timeoutInMillis);
MultipartBody.Builder multiBuilder = new MultipartBody.Builder();
multiBuilder.setType(MultipartBody.FORM);
if (!CollectionUtils.isEmpty(files)) {
files.forEach(multipartFile -> {
String fieldName = FieldName();
String fileName = FileName();
byte[] content = Content();
multiBuilder.addFormDataPart(fieldName, fileName, ate(OCTET_STREAM, content));
});
}
MultipartBody requestBody = multiBuilder.build();
Request request = new Request.Builder().url(url).post(requestBody).build();
return getResponse(client, request);
}
public static byte[] downloadFile(String url) throws IOException {
return downloadFile(url, TIMEOUT_MILLIS);
}
public static byte[] downloadFile(String url, long timeoutInMillis) throws IOException {
OkHttpClient client = getOkHttpClient(timeoutInMillis);
Request request = new Request.Builder().url(url).get().build();
try (Response response = wCall(request).execute()) {
if (!response.isSuccessful()) {
return null;
}
return response.body().bytes();
} catch (IOException e) {
throw e;
}
}
private static OkHttpResp getResponse(OkHttpClient client, Request request) throws IOException {
OkHttpResp resp = new OkHttpResp();
OkHttpResp resp = new OkHttpResp();
// 确保Response和ResponseBody关闭
try (Response response = wCall(request).execute()) {
if (!response.isSuccessful()) {
resp.setSuccessful(false);
}
ResponseBody body = response.body();
resp.setSuccessful(true);
resp.setRespStr(body.string());
resp.setRespHeaders(response.headers());
resp.tType());
resp.tLength());
return resp;
} catch (IOException e) {
throw e;
}
}
private static void addHeaders(Map<String, Object> reqHeaders, Request.Builder reqBuilder) {    if (CollectionUtils.isEmpty(reqHeaders)) {
return;
}
reqHeaders.forEach((headerName, headerValue) -> {
reqBuilder.addHeader(headerName, String.valueOf(headerValue));
});
}
public static class MultipartFile {
/**
* ⽂件域名,相当于表单中⽂件域名
*/
private String fieldName;
private String fileName;
private byte[] content;
public MultipartFile() {
}
public MultipartFile(String fieldName, String fileName, byte[] content) {
this.fieldName = fieldName;
this.fileName = fileName;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public byte[] getContent() {
return content;
}
public void setContent(byte[] content) {
}
}
public static class OkHttpResp {
private String respStr;
private Headers respHeaders;
private MediaType contentType;
private long contentLength;
private boolean successful;
public String getRespStr() {
return respStr;
}
public Headers getRespHeaders() {
return respHeaders;
}
public MediaType getContentType() {
return contentType;
}
public long getContentLength() {
return contentLength;
}
public boolean isSuccessful() {
connect下载
return successful;
}
public void setRespStr(String respStr) {
}
public void setRespHeaders(Headers respHeaders) {
}
public void setContentType(MediaType contentType) {
}
public void setContentLength(long contentLength) {
}
public void setSuccessful(boolean successful) {
this.successful = successful;
}
@Override
public String toString() {
flectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);    }
}
}
对阿⾥FastJSONj进⾏JavaBean到json字符串映射的简单封装。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。