如果想看Okhttp3的各种请求详细使用,请查看博客Android Okhttp3的使用(很全面,包含Post提交字符串、键值对、表单、上传文件、无参请求和Get有参无参请求,还有自动添加token)_ErwinNakajima的博客-CSDN博客_okhttp3 token
Okhttp3 get请求一般不携带参数,如果携带头部header和参数,那就这样处理。
//携带的参数
Map bodyParams = new HashMap<>();
bodyParams.put("param1", "xxx");
bodyParams.put("param2", "xxx");
Map headParams = new HashMap<>();
headParams.put("headParam", "xxx");
1、初始化Okhttp3。
(1)Okhttp3的初始化。
private static final String TAG = Okhttp3Manager.class.getSimpleName();
private OkHttpClient client;
private static Okhttp3Manager manager;
public static final int UPDATA = 666;
/**
* 单例模式,所以构造函数私有化
*/
private Okhttp3Manager() {
//创建OkHttpClient对象
client = new OkHttpClient.Builder()
.connectTimeout(5000, TimeUnit.MILLISECONDS) //连接超时
.readTimeout(5000, TimeUnit.MILLISECONDS) //读取超时
.writeTimeout(5000, TimeUnit.MILLISECONDS) //写入超时
.sslSocketFactory(SSLSocketManager.getSSLSocketFactory())//配置(https请求才需要配置,http请求不用)
.hostnameVerifier(SSLSocketManager.getHostnameVerifier())//配置(https请求才需要配置,http请求不用)
// .proxy(Proxy.NO_PROXY)
.build();
}
/**
* 线程安全的单例模式,整个项目中只有一个okhttp3实例
*
* @return
*/
public static Okhttp3Manager getInstance() {
if (manager == null) {
synchronized (Okhttp3Manager.class) {
if (manager == null) {
manager = new Okhttp3Manager();
}
}
}
return manager;
}
(2)添加SSLSocketManager类(https请求才需要写并配置,http请求不用)。
package com.phone.common_library.manager;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* okhttp3忽略https证书
*/
public class SSLSocketManager {
/**
* 获取这个SSLSocketFactory
*
* @return
*/
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
*
* @return
*/
public static TrustManager[] getTrustManager() {
TrustManager[] trustManager = 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[]{};
}
}
};
return trustManager;
}
/**
* 获取hostnameVerifier
*
* @return
*/
public static HostnameVerifier getHostnameVerifier() {
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
};
return hostnameVerifier;
}
}
2、get请求,添加请求参数和header参数,异步方式。
/**
* get请求,添加请求参数和header参数,异步方式,是在子线程中执行的,需要切换到主线程才能更新UI
*
* @param url
* @param headerParams
* @param bodyParams
* @param onCommonSingleParamCallback
*/
public void getAsync(String url,
Map headerParams,
Map bodyParams,
OnCommonSingleParamCallback onCommonSingleParamCallback) {
String urlNew = url;
// 设置HTTP请求参数
urlNew += getBodyParams(bodyParams);
Headers headers = setHeaderParams(headerParams);
//2.创建Request对象,设置一个url地址,设置请求方式。
Request request = new Request.Builder().url(urlNew).get().headers(headers).build();
// Request request = new Request.Builder()
// .url(url)
// .get()//默认就是GET请求,可以不写(最好写上,要清晰表达出来)
// .build();
//3.创建一个call对象,参数就是Request请求对象
Call call = client.newCall(request);
//4 执行Call
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
LogManager.i(TAG, "getAsync onFailure e*******" + e.toString());
LogManager.i(TAG, "getAsync onFailure e detailMessage*******" + e.getMessage());
MainThreadManager mainThreadManager = new MainThreadManager();
mainThreadManager.setOnSubThreadToMainThreadCallback(new OnSubThreadToMainThreadCallback() {
@Override
public void onSuccess() {
onCommonSingleParamCallback.onError(BaseApplication.getInstance().getResources().getString(R.string.network_sneak_off));
}
});
mainThreadManager.subThreadToUIThread();
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
String responseString = response.body().string();
LogManager.i(TAG, "getAsync onResponse responseString*****" + responseString);
MainThreadManager mainThreadManager = new MainThreadManager();
mainThreadManager.setOnSubThreadToMainThreadCallback(new OnSubThreadToMainThreadCallback() {
@Override
public void onSuccess() {
if (!isEmpty(responseString)) {
BaseResponse baseResponse;
try {
baseResponse = JSON.parseObject(responseString, BaseResponse.class);
} catch (Exception e) {
//如果不是标准json字符串,就返回错误提示
onCommonSingleParamCallback.onError(BaseApplication.getInstance().getResources().getString(R.string.server_sneak_off));
return;
}
onCommonSingleParamCallback.onSuccess(responseString);
} else {
onCommonSingleParamCallback.onError(BaseApplication.getInstance().getResources().getString(R.string.server_sneak_off));
}
}
});
mainThreadManager.subThreadToUIThread();
}
});
}
/**
* 添加参数
*
* @param bodyParams
* @return
*/
private String getBodyParams(Map bodyParams) {
//1.添加请求参数
//遍历map中所有参数到builder
if (bodyParams != null && bodyParams.size() > 0) {
StringBuffer stringBuffer = new StringBuffer("?");
for (String key : bodyParams.keySet()) {
if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(bodyParams.get(key))) {
//如果参数不是null并且不是"",就拼接起来
stringBuffer.append("&");
stringBuffer.append(key);
stringBuffer.append("=");
stringBuffer.append(bodyParams.get(key));
}
}
return stringBuffer.toString();
} else {
return "";
}
}
/**
* 添加headers
*
* @param headerParams
* @return
*/
private Headers setHeaderParams(Map headerParams) {
Headers headers = null;
Headers.Builder headersbuilder = new Headers.Builder();
if (headerParams != null && headerParams.size() > 0) {
for (String key : headerParams.keySet()) {
if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(headerParams.get(key))) {
//如果参数不是null并且不是"",就拼接起来
headersbuilder.add(key, headerParams.get(key));
}
}
}
headers = headersbuilder.build();
return headers;
}