okhttp 使用
构建post 表单请求
/**
* 构造POST 表单请求
* @param url url
* @param fromParam form 表单参数
* @param headers 自定义请求头
* @return 响应流
*/
@SneakyThrows
public static Response doPostForm(String url, Map<String, Object> fromParam, Map<String, Object> headers) {
//构造请求参数
HttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
//构造请求体
MultipartBody.Builder mBuilder = new MultipartBody.Builder();
mBuilder.setType(MultipartBody.FORM);
if (MapUtil.isNotEmpty(fromParam))
fromParam.forEach((k, v) -> mBuilder.addFormDataPart(k, String.valueOf(v)));
MultipartBody multipartBody = mBuilder.build();
Request.Builder builder = new Request.Builder();
if (MapUtil.isNotEmpty(headers))
headers.forEach((k, v) -> builder.addHeader(k, String.valueOf(v)));
Request request = builder.url(urlBuilder.build().toString()).post(multipartBody).build();
//发出同步请求
return new OkHttpClient.Builder().build().newCall(request).execute();
}
构建get请求
/**
* 构造GET 请求
* @param url url
* @param param 参数map
* @param headers 自定义请求头
* @return 响应流
*/
@SneakyThrows
public static Response doGet(String url, Map<String, Object> param, Map<String, Object> headers) {
//构造请求参数
HttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
if (MapUtil.isNotEmpty(param))
param.forEach((k, v) -> urlBuilder.addQueryParameter(k, String.valueOf(v)));
Request.Builder builder = new Request.Builder();
if (MapUtil.isNotEmpty(headers))
headers.forEach((k, v) -> builder.addHeader(k, String.valueOf(v)));
Request request = builder.url(urlBuilder.build().toString()).get().build();
//发出同步请求
return new OkHttpClient.Builder().build().newCall(request).execute();
}
构建post请求
/**
* 构造携带accessToken POST 请求
* @param url url
* @param fromParam query请求参数 例:?userId=1&userName=张三
* @param bodyParam 传参 raw格式
* @return 响应流
*/
@SneakyThrows
public static Response doPost(String url, Map<String, Object> fromParam, Map<String, Object> bodyParam){
//构造请求参数
HttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
if (MapUtil.isNotEmpty(fromParam))
fromParam.forEach((k, v) -> urlBuilder.addQueryParameter(k, String.valueOf(v)));
//构造请求体
RequestBody requestBody = RequestBody.
create(MediaType.parse("application/json;charset=utf-8"), JSON.toJSONString(bodyParam));
Request.Builder builder = new Request.Builder();
Request request = builder.url(urlBuilder.build().toString()).post(requestBody).build();
//发出同步请求
return new OkHttpClient.Builder().build().newCall(request).execute();
}
相关导包
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.nacos.common.utils.MapUtil;
import lombok.SneakyThrows;
import okhttp3.*;
import org.apache.commons.lang3.ObjectUtils;
import java.util.Map;
import java.util.Objects;
处理Response转为JsonObject
/**
* okhttp3 响应处理,返回jsonObject
* @param response 响应流
* @return JSONObject
*/
public static JSONObject getResponseObject(Response response){
try {
if (response != null && response.body() != null) {
return JSON.parseObject(response.body().byteStream(), JSONObject.class, Feature.OrderedField);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* okhttp3 响应处理
* @param response 响应流
* @param cls class
* @return class
*/
public static <T> T getResponseObject(Response response, Class<T> cls){
try {
if (response != null && response.body() != null) {
return JSON.parseObject(response.body().byteStream(), cls, Feature.OrderedField);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* okhttp3 响应处理
* @param response 响应流
* @param cls class
* @param feature feature
* @return class
*/
public static <T> T getResponseObject(Response response, Class<T> cls, Feature feature){
try {
if (response != null && response.body() != null) {
return JSON.parseObject(response.body().byteStream(), cls, feature);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
忽略 ssl 证书
/**
* 创建ssl http client
* @return 忽略证书的https请求
*/
public static OkHttpClient getSllHttpClient() {
return new OkHttpClient.Builder()
.sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), SSLSocketClient.getX509TrustManager())
.hostnameVerifier(SSLSocketClient.getHostnameVerifier())
.build();
}
import javax.net.ssl.*;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Arrays;
/**
* 忽略SSL验证
*/
public class SSLSocketClient {
//获取这个SSLSocketFactory
public static SSLSocketFactory getSSLSocketFactory() {
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, getTrustManager(), new SecureRandom());
return sslContext.getSocketFactory();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//获取TrustManager
private static TrustManager[] getTrustManager() {
return new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}
};
}
//获取HostnameVerifier
public static HostnameVerifier getHostnameVerifier() {
return (s, sslSession) -> true;
}
public static X509TrustManager getX509TrustManager() {
X509TrustManager trustManager = null;
try {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
}
trustManager = (X509TrustManager) trustManagers[0];
} catch (Exception e) {
e.printStackTrace();
}
return trustManager;
}
}
文章来源地址https://www.toymoban.com/news/detail-531119.html
文章来源:https://www.toymoban.com/news/detail-531119.html
到了这里,关于okhttp 的使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!