package com.example.com.lixiaolong_04_27_.okhttp; import android.os.Handler; import android.os.Looper; import java.io.IOException; import java.util.Map; import java.util.concurrent.TimeUnit; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor; /** * Created by 李小龙 on 2018/4/27. */ public class OkhttpUtils { private static OkhttpUtils instance; private OkHttpClient okHttpClient; private Handler handler; private OkhttpUtils(){ HttpLoggingInterceptor logging = new HttpLoggingInterceptor();//拦截器 logging.setLevel(HttpLoggingInterceptor.Level.BODY); okHttpClient = new OkHttpClient.Builder()//创建Ok .connectTimeout(15, TimeUnit.SECONDS)//连接超时 .writeTimeout(20, TimeUnit.SECONDS)//写入超时 .readTimeout(20, TimeUnit.SECONDS)//读取超时 //.addInterceptor(new MyInterceptor())//添加拦截器 .addInterceptor(logging)//添加拦截器 .build();// handler = new Handler(Looper.getMainLooper()); } //调用 //调用 //调用 public static OkhttpUtils getInstance() { if (instance == null) { instance = new OkhttpUtils(); } return instance; } //get方法 //get方法 //get方法 public void doGet(String url, final OkhttpListener okhttpListener){ //创建Request final Request request = new Request.Builder() .url(url) .build(); //发送请求 okHttpClient.newCall(request).enqueue(new Callback() { public void onFailure(Call call, final IOException e) { handler.post(new Runnable() { @Override public void run() { okhttpListener.No(e); } }); } public void onResponse(Call call, Response response) throws IOException { //拿到服务器返回的数 final String string = response.body().string(); handler.post(new Runnable() { @Override public void run() { okhttpListener.Ok(string); } }); } }); } //post方法 //post方法 //post方法 public void doPost(String url, Map<String, String> params, final OkhttpListener okhttpListener) { FormBody.Builder builder = new FormBody.Builder(); for (Map.Entry<String, String> entry : params.entrySet()) { builder.add(entry.getKey(), entry.getValue()); } //创建FormBody FormBody formBody = builder.build(); //创建Request Request request = new Request.Builder() .url(url) .post(formBody) .build(); //请求数据 okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { handler.post(new Runnable() { @Override public void run() { okhttpListener.No(e); } }); } public void onResponse(Call call, Response response) throws IOException { //拿到服务器返回的数据 final String string = response.body().string(); handler.post(new Runnable() { @Override public void run() { okhttpListener.Ok(string); } }); } }); } } 实现接口回调方法
public interface OkhttpListener { void Ok(String str); //成功的方法 void No(Exception e);//失败的方法 }