OkHttpUtols
public class OkHttpUtils {
private static OkHttpUtils okHttpUtils;
private OkHttpClient okHttpClient;
private OkHttpUtils(){
//创建拦截器对象
HttpLoggingInterceptor httpLoggingInterceptor=new HttpLoggingInterceptor();
//配置日志拦截器
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient= new OkHttpClient.Builder()
.writeTimeout(2000,TimeUnit.MICROSECONDS)
.
.addInterceptor(httpLoggingInterceptor)
.build();
}
public static OkHttpUtils getinstance(){
if(okHttpUtils==null){
synchronized (OkHttpUtils.class){
if(okHttpUtils==null){
okHttpUtils=new OkHttpUtils();
}
}
}
return okHttpUtils;
}
//get封装
public void getData(String url,HashMap<String,String>parms,final RequestCallBack requestCallBack ){
StringBuilder urlsb = new StringBuilder();
String allUrl = "";
for (Map.Entry<String,String> stringStringEntry:parms.entrySet() ){
urlsb.append("?").append(stringStringEntry.getKey()).append("=").append(stringStringEntry.getValue()).append("&");
}
allUrl = url+urlsb.toString().substring(0,urlsb.length()-1);
System.out.println("url:" + allUrl);
Request request =new Request.Builder()
.url(allUrl)
.get()
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
//请求失败
@Override
public void onFailure(Call call, IOException e) {
if(requestCallBack!=null){
requestCallBack.failure(call,e);
}
}
//请求成功
@Override
public void onResponse(Call call, Response response) throws IOException {
if(requestCallBack!=null){
requestCallBack.onResponse(call,response);
}
}
});
}
//post请求方式
public void postData(String url,HashMap<String,String>parms,final RequestCallBack requestCallBack){
FormBody.Builder formBodybuilder = new FormBody.Builder();
if(parms!=null && parms.size()>0){
for (Map.Entry<String,String> stringStringEntry:parms.entrySet() ){
formBodybuilder.add(stringStringEntry.getKey(),stringStringEntry.getValue());
}
}
Request request = new Request.Builder()
.url(url)
.post(formBodybuilder.build())
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
if (requestCallBack != null) {
requestCallBack.failure(call, e);
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (requestCallBack != null) {
requestCallBack.onResponse(call,response);
}
}
});
}
}
RequestCallBack
interface RequestCallBack {
void failure(Call call, IOException e);
void onResponse(Call call, Response response);