OkHttp Get请求

依赖

implementation 'com.squareup.okhttp3:okhttp:3.11.0' 
implementation 'com.squareup.okio:okio:1.11.0' 
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'

创建OkHttp

package com.example.wekk3.utils;
import android.os.Handler;
import android.os.Looper;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
public class OkHttpUtils {

private static volatile OkHttpUtils mInstance;
private OkHttpClient mClient;
private Handler mHandler = new Handler(Looper.getMainLooper());
/** * 第一步,写一个单例,这里用的懒汉式,也可以使用饿汉 * @return */
public static OkHttpUtils getInstance() {
    if (mInstance == null) {
        synchronized (OkHttpUtils.class) {
            if (null == mInstance) {
                mInstance = new OkHttpUtils();
            }
        }
    }
    return mInstance;
}
/** * 完成构造方法,OkHttpClient */
private OkHttpUtils() {
       HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
       interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        /** * 使用构造者模式 * 设置连接超时 * 读取超时 * 写超时 * 添加拦截器 */
         mClient = new OkHttpClient.Builder()
           .connectTimeout(10, TimeUnit.SECONDS)
           .readTimeout(10, TimeUnit.SECONDS)
           .writeTimeout(10, TimeUnit.SECONDS)
           .addInterceptor(interceptor) .build();
        }
/** * 网络同步方法
 * * 创建一个get请求
 * * 设置一个路径
 * * * 通过mClient.newCall建一个Call对象
 * * 调用同步请求方法
 * * * @param url 
 * * @param callBack 
 * * @param clazz 
 * * @return 
 * * @throws IOException 
 * */
public String getExecute(String url, final CallBack callBack, final Class clazz) throws IOException {
        Request request = new Request.Builder()
           .get()
           .url(url)
           .build();
        Call call = mClient.newCall(request); Response response = call.execute();
            return byte2String(response.body().bytes());
        }
/** * 异步的get方法
* * 创建一个请求
* * 创建一个call
* * 调用异步请求
* * * @param url
* * @param callBack
* * @param clazz
* */
    public void getEnqueue(final String url, final CallBack callBack, final Class clazz) {
          Request request = new Request.Builder()
            .get()
            .url(url)
            .build();
        Call call = mClient.newCall(request); call.enqueue(new Callback() {
        //网络请求连接失败
        @Override
         public void onFailure(Call call, final IOException e) {
             mHandler.post(new Runnable() {
              @Override
              public void run() {
                callBack.failed(e);
              }
            });
        }
   //网络请求连接成功
     @Override
    public void onResponse(Call call, Response response) throws IOException {
             String result = response.body().string();
             Gson gson = new Gson();
             final Object o = gson.fromJson(result, clazz);
             mHandler.post(new Runnable() {
             @Override
             public void run() {
                 callBack.success(o);
             }
       });
    }
  });
}
 private static String byte2String(byte[] bytes) {

           return new String(bytes);
      }
}

猜你喜欢

转载自blog.csdn.net/weixin_43926099/article/details/88066401