关于OkHttp的基础使用可以看我之前写的这篇文章
但是每次写网络请求,都要写一大堆重复的东西,所以肯定要封装一下,简化使用。
主要分为四个类:
一、请求回调的接口ReqCallBack
public interface ReqCallBack<T> {
/**
* 响应成功
*/
void onReqSuccess(T result);
/**
* 响应失败
*/
void onReqFailed(String errorMsg);
}
二、post请求时我们通常要传递的参数
//post方式接口所需参数的键值对
public class RequestParameter implements Serializable {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
private String name;
private String value;
public RequestParameter(String name,String value){
this.name=name;
this.value=value;
}
}
三、网络请求入口类OkHttpNetUtil
在整个项目中我们只需要一个OkHttpClient对象,不同的网络请求只需要创建不同的Requset对象和Call对象。所以我们将OkHttpClient对象的创建写成单例模式。
我们自己写一个网络请求的类OkHttpNetUtil。
在这个类中我们通过单例出的对象发起请求,创建request请求。
public class OkHttpNetUtil {
public static final int TYPE_GET = 0;//get请求
public static final int TYPE_POST_JSON = 1;//post请求参数为json
public static final int TYPE_POST_FORM = 2;//post请求参数为表单
private static OkHttpNetUtil okHttpNetUtil;
public final OkHttpClient client;
//构造函数私有
private OkHttpNetUtil() {
client = initOkHttpClient();
}
private OkHttpClient initOkHttpClient() {
//初始化的时候可以自定义一些参数
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(10000, TimeUnit.MILLISECONDS)//设置读取超时为10秒
.connectTimeout(10000, TimeUnit.MILLISECONDS)//设置链接超时为10秒
.build();
return okHttpClient;
}
//单例
public static OkHttpNetUtil getOkHttpClient() {
if (okHttpNetUtil == null) {
synchronized (OkHttpNetUtil.class) {
if (okHttpNetUtil == null) {
okHttpNetUtil = new OkHttpNetUtil();
}
}
}
return okHttpNetUtil;
}
/**
* okHttp同步请求统一入口
*
* @param url 接口地址
* @param requestType 请求类型
* @param parameters 请求参数
**/
private void createRequest(String url, int requestType, List<RequestParameter> parameters) throws IOException {
switch (requestType) {
case TYPE_GET:
OkHttpRequest.requestGet(url, parameters);
break;
case TYPE_POST_JSON:
OkHttpRequest.requestPostByJson(url, parameters);
break;
case TYPE_POST_FORM:
OkHttpRequest.requestPostByForm(url, parameters);
break;
}
}
/**
* okHttp异步请求统一入口
*
* @param url 接口地址
* @param requestType 请求类型
* @param parameters 请求参数
* @param callBack 请求返回数据回调
* @param <T> 数据泛型
**/
private <T> Call createRequest(String url, int requestType, List<RequestParameter> parameters, ReqCallBack<T> callBack) throws IOException {
Call call = null;
switch (requestType) {
case TYPE_GET:
call = OkHttpRequest.requestGet(url, parameters, callBack);
break;
case TYPE_POST_JSON:
call=OkHttpRequest.requestPostByJson(url, parameters, callBack);
break;
case TYPE_POST_FORM:
call=OkHttpRequest.requestPostByForm(url, parameters, callBack);
break;
}
return call;
}
}
四、具体请求的封装OkHttpRequest
public class OkHttpRequest {
private static Handler okHttpHandler= new Handler(Looper.getMainLooper());//全局处理子线程和M主线程通信
/**
* okHttp post同步请求 form
* @param url 接口地址
* @param parameters 请求参数
*/
public static String requestPostByForm(String url, List<RequestParameter> parameters) throws IOException {
//创建一个FormBody.Builder
FormBody.Builder builder=new FormBody.Builder();
if (parameters!=null&¶meters.size()>0){
for (final RequestParameter p : parameters) {
builder.add(p.getName(),p.getValue());
}
}
RequestBody formBody=builder.build();
Request request=new Request.Builder().url(url).post(formBody).build();
//创建一个Call
final Call call = OkHttpNetUtil.getOkHttpClient().client.newCall(request);
//执行请求
Response response = call.execute();
if (response.isSuccessful()){
return response.body().string();
}
return null;
}
/**
* okHttp post同步请求 json
* @param url 接口地址
* @param parameters 请求参数
*/
public static String requestPostByJson(String url, List<RequestParameter> parameters) throws IOException {
final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
StringBuffer paramBuffer=new StringBuffer();
if ((parameters != null) && (parameters.size() > 0)){
for (final RequestParameter p : parameters) {
if (paramBuffer.length() == 0) {
paramBuffer.append(p.getName() + "="
+ p.getValue());
}
else {
paramBuffer.append(p.getName() + "="
+ p.getValue());
}
}
}
String json=paramBuffer.toString();
RequestBody requestBody=RequestBody.create(JSON,json);
Request request=new Request.Builder().url(url).post(requestBody).build();
Call call=OkHttpNetUtil.getOkHttpClient().client.newCall(request);
Response reponse=call.execute();
if (reponse.isSuccessful()){
return reponse.body().string();
}
return null;
}
/**
* okHttp get同步请求
* @param url 接口地址
* @param parameters 请求参数
*/
public static String requestGet(String url, List<RequestParameter> parameters) throws IOException {
//有参
if ((parameters != null) && (parameters.size() > 0)){
final StringBuffer paramBuffer = new StringBuffer();
for (final RequestParameter p : parameters) {
if (paramBuffer.length() == 0) {
paramBuffer.append(p.getName() + "="
+ p.getValue());
} else {
paramBuffer.append("&" + p.getName() + "="
+ p.getValue());
}
}
String newUrl = url + "?" + paramBuffer.toString();
Request request=new Request.Builder().url(newUrl).build();
Call call=OkHttpNetUtil.getOkHttpClient().client.newCall(request);
Response reponse=call.execute();
if (reponse.isSuccessful()){
return reponse.body().string();
}
return null;
}
//无参
else {
Request request=new Request.Builder().url(url).build();
Call call=OkHttpNetUtil.getOkHttpClient().client.newCall(request);
Response response=call.execute();
if (response.isSuccessful()){
return response.body().string();
}
return null;
}
}
/**
* okHttp get 异步请求
* @param url 接口地址
* @param parameters 请求参数
* @param callBack 请求返回数据回调
*/
public static <T> Call requestGet(String url, List<RequestParameter> parameters, final ReqCallBack<T> callBack) throws IOException {
//有参
if ((parameters != null) && (parameters.size() > 0)){
final StringBuffer paramBuffer = new StringBuffer();
for (final RequestParameter p : parameters) {
if (paramBuffer.length() == 0) {
paramBuffer.append(p.getName() + "="
+ p.getValue());
} else {
paramBuffer.append("&" + p.getName() + "="
+ p.getValue());
}
}
String newUrl = url + "?" + paramBuffer.toString();
Request request=new Request.Builder().url(newUrl).build();
Call call=OkHttpNetUtil.getOkHttpClient().client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
failedCallBack("访问失败", callBack);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String string = response.body().string();
successCallBack((T) string, callBack);
} else {
failedCallBack("服务器错误", callBack);
}
}
});
return call;
}
//无参
else {
Request request=new Request.Builder().url(url).build();
Call call=OkHttpNetUtil.getOkHttpClient().client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
failedCallBack("访问失败", callBack);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String string = response.body().string();
successCallBack((T) string, callBack);
} else {
failedCallBack("服务器错误", callBack);
}
}
});
return call;
}
}
/**
* okHttp post 异步请求 json
* @param url 接口地址
* @param parameters 请求参数
* @param callBack 请求返回数据回调
*/
public static <T> Call requestPostByJson(String url, List<RequestParameter> parameters, final ReqCallBack<T> callBack) {
//创建一个FormBody.Builder
FormBody.Builder builder=new FormBody.Builder();
if (parameters!=null&¶meters.size()>0){
for (final RequestParameter p : parameters) {
builder.add(p.getName(),p.getValue());
}
}
RequestBody formBody=builder.build();
Request request=new Request.Builder().url(url).post(formBody).build();
//创建一个Call
final Call call = OkHttpNetUtil.getOkHttpClient().client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
failedCallBack("访问失败", callBack);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String string = response.body().string();
successCallBack((T) string, callBack);
} else {
failedCallBack("服务器错误", callBack);
}
}
});
return call;
}
/**
* okHttp post 异步请求 form
* @param url 接口地址
* @param parameters 请求参数
* @param callBack 请求返回数据回调
*/
public static <T> Call requestPostByForm(String url, List<RequestParameter> parameters, final ReqCallBack<T> callBack) throws IOException {
//创建一个FormBody.Builder
FormBody.Builder builder=new FormBody.Builder();
if (parameters!=null&¶meters.size()>0){
for (final RequestParameter p : parameters) {
builder.add(p.getName(),p.getValue());
}
}
RequestBody formBody=builder.build();
Request request=new Request.Builder().url(url).post(formBody).build();
//创建一个Call
final Call call = OkHttpNetUtil.getOkHttpClient().client.newCall(request);
//执行请求
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
failedCallBack("访问失败", callBack);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String string = response.body().string();
successCallBack((T) string, callBack);
} else {
failedCallBack("服务器错误", callBack);
}
}
});
return call;
}
private static <T> void successCallBack(final T result, final ReqCallBack<T> callBack) {
okHttpHandler.post(new Runnable() {
@Override
public void run() {
if (callBack != null) {
callBack.onReqSuccess(result);
}
}
});
}
private static <T> void failedCallBack(final String errorMsg, final ReqCallBack<T> callBack) {
okHttpHandler.post(new Runnable() {
@Override
public void run() {
if (callBack != null) {
callBack.onReqFailed(errorMsg);
}
}
});
}
}
五、具体使用
一个get请求:
ReqCallBack<String> callback=new ReqCallBack<String>() {
@Override
public void onReqSuccess(String result) {
textview.setText(result);
}
@Override
public void onReqFailed(String errorMsg) {
textview.setText(errorMsg);
}
};
OkHttpRequest.requestGet(netUrl, null,callback);
一个post请求
ReqCallBack<String> callback=new ReqCallBack<String>() {
@Override
public void onReqSuccess(String result) {
textview.setText(result);
}
@Override
public void onReqFailed(String errorMsg) {
textview.setText(errorMsg);
}
};
List<RequestParameter> parameters=new ArrayList<>();
String value="xxxxxxxx";
parameters.add(new RequestParameter("key",value));
OkHttpRequest.requestPostByForm(netUrl,parameters,callback);