使用之前导入依赖
compile 'com.squareup.okhttp3:okhttp:3.9.1'
然后进行封装
import android.os.Handler;
import android.util.Log;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OKHttpUtils {
private static OKHttpUtils okHttpUtils;
private static Handler handler = new Handler();
//私有化构造方法
public OKHttpUtils() {
}
/**
* 获取OKhttpClient实例化
*/
public static OKHttpUtils getInstance() {
if (null == okHttpUtils) {
synchronized (OKHttpUtils.class) {
if (null == okHttpUtils) {
okHttpUtils = new OKHttpUtils();
}
}
}
return okHttpUtils;
}
/**
* 封装的异步Get请求
*/
public void doGet(String path, Map<String, String> map, final OKHttpCallBack okHttpCallBack) {
//创建一个字符串容器
StringBuilder sb = null;
if (map.size() == 0) {
if (null == sb) {
sb = new StringBuilder();
sb.append(path);
}
} else {
for (String key : map.keySet()) {
if (null == sb) {
sb = new StringBuilder();
sb.append(path);
sb.append("?");
} else {
sb.append("&");
}
sb.append(key).append("=").append(map.get(key));
}
}
// StringBuilder sb = new StringBuilder();
// sb.append(path).append("?");
// for(Map.Entry entry:map.entrySet()){
// sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
// }
//
// sb.deleteCharAt(sb.lastIndexOf("&"));
//Log.e("WWWWW",sb.toString());
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new CommonParamsInterceptor())
.build();
Request request = new Request.Builder()
.url(sb.toString())
.get()
.build();
//OKHttp 网络
Call call = okHttpClient.newCall(request);
//异步请求
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//请求失败
okHttpCallBack.onFailed(e.getMessage());
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
final String str = response.body().string();
//Log.i("fff", "sssss"+str + "");
//请求成功
handler.post(new Runnable() {
@Override
public void run() {
okHttpCallBack.onSuccess(str);
}
});
}
});
}
}
shixianjiekou
public interface OKHttpCallBack {
void onSuccess(String str);
void onFailed(String message);
}
拦截器
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* 应用层拦截器
*/
public class CommonParamsInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
//得到原始的请求对象
Request request = chain.request();//原始的请求项
//得到请求方式 Get 、Post
String method = request.method();
if("GET".equals(method)){
//取出原始的url
String oldUrl = request.url().toString();
System.out.println("原始的url : "+oldUrl);
String newUrl = oldUrl + "&source=android";
System.out.println("一个新的请求url : "+newUrl);
//构建新的request
request = new Request.Builder()
.url(newUrl)
.build();
}else if("POST".equals(method)){
//1,取出旧的参数以及url
FormBody body = (FormBody) request.body();
//取出旧的Url
String oldUrl = request.url().toString();
//构建一个新的FormBody
FormBody.Builder newFormBody = new FormBody.Builder();
for (int i = 0; i < body.size();i++){
String key = body.name(i);//keywors
String value = body.value(i);//value
newFormBody.add(key,value);
}
//公共参数
newFormBody.add("source","android");
//新构建的reqeust
request = new Request.Builder()
.url(oldUrl)
.post(newFormBody.build())
.build();
//2.构建请求体
//3.重新执行
}
return chain.proceed(request);
}
}
OK没封装的使用
import android.os.Handler; import com.bwie.newjingd.bean.Car_Select; import com.bwie.newjingd.bean.Lunbotu; import com.bwie.newjingd.bean.TuijianBean; import com.bwie.newjingd.presenter.Car_Select_p; import com.bwie.newjingd.utils.OKHttpCallBack; import com.bwie.newjingd.utils.OKHttpUtils; import com.google.gson.Gson; import java.util.HashMap; import java.util.List; import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class Car_Model_Select { private final Handler handler=new Handler(); public void select(final Car_Select_p car_select_p){ new Thread() { @Override public void run() { super.run(); try { //HttpClient请求 OkHttpClient okHttpClient = new OkHttpClient(); Request request = new Request.Builder() .get()//请求方式 .url("http://120.27.23.105/product/getCarts?source=android&uid=88")//请求网址 .build();//创建,开始请求 //准备发送请求 Call call = okHttpClient.newCall(request); //执行请求 Response response = call.execute(); //得到请求结果 String result = response.body().string(); Gson gson = new Gson(); Car_Select car_select = gson.fromJson(result, Car_Select.class); final List<Car_Select.DataBean> data = car_select.getData(); handler.post(new Runnable() { @Override public void run() { car_select_p.onSuccess(data); } }); } catch (Exception e) { e.printStackTrace(); } } }.start(); } }