天天看點

Okhttp3 簡單單例封裝

/**
 * User:bick
 * Created by Administrator-10-24 09 : 30
 */

import android.app.Activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
/**
  * Ok封裝工具類
  */

import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by asus on 2017/10/15.
 */

public class OkhttpUtils {

    public Activity context;
    //單例模式,聲明
    public static OkhttpUtils okhttpInstanse;

    public OkhttpUtils(Activity context) {
        this.context = context;
    }
    /**
     * 提供暴露方法
     *
     */
    public static OkhttpUtils getInstance(Activity context){
        if(okhttpInstanse==null)
        {
            synchronized (OkhttpUtils.class){
                if(okhttpInstanse==null)
                {
                    okhttpInstanse=new OkhttpUtils(context);
                }
            }
        }
        return okhttpInstanse;
    }
    public void call(String okhttpMethod, String url, Map<String,Object> map, final OkhttpCall okhttpCall){
 
        Request request=null;
        OkHttpClient client =
                new OkHttpClient.Builder()
                        .addInterceptor(new LogInterceptor())
                        .connectTimeout(10, TimeUnit.SECONDS)
                        .readTimeout(10, TimeUnit.SECONDS)
                        .writeTimeout(10, TimeUnit.SECONDS)
                        .retryOnConnectionFailure(false)
                        .build();
        if(map!=null&&map.entrySet().size()>0) {

            if (okhttpMethod.equalsIgnoreCase("GET")) {
                String mUrl = url + "?";
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    mUrl+=entry.getKey()+"="+entry.getValue()+"&";
                }
                request=new Request.Builder().url(mUrl).get().build();
            }
            else if(okhttpMethod.equalsIgnoreCase("POST"))
            {
                FormBody.Builder formBody=new FormBody.Builder();
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    formBody.add(entry.getKey(),entry.getValue().toString());
                }
                request=new Request.Builder().url(url).post(formBody.build()).build();
            }

        }
        if(request!=null) {
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    String s = e.toString();
                    okhttpCall.onFailure(call,e);
                }

                @Override
                public void onResponse(final Call call, Response response) throws IOException {
                    //子線程加載資料
                    final StringBuffer result=new StringBuffer();
                    InputStream inputStream=null;
                    BufferedReader bufferedReader=null;
                    if(response!=null&&response.isSuccessful()) {
                        inputStream = response.body().byteStream();

                        bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                        String line = "";
                        while ((line = bufferedReader.readLine()) != null) {
                            result.append(line);
                        }
                        context.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                okhttpCall.onResponse(call,result.toString());
                            }
                        });
                    }
                }
            });
        }

    }

    public interface OkhttpCall{
        void onFailure(Call call,IOException e);
        void onResponse(Call call, String response);
    }
}
           

// 網絡攔截器

/**
 * User:Bcik
 * Created by Administrator-10-24 09 : 32
 */

public class LogInterceptor implements Interceptor {

    public static String TAG = "LogInterceptor";

    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request request = chain.request();
        long startTime = System.currentTimeMillis();
        Response response = chain.proceed(chain.request());
        long endTime = System.currentTimeMillis();
        long duration=endTime-startTime;
        MediaType mediaType = response.body().contentType();
        String content = response.body().string();
        Log.d(TAG,"\n");
        Log.d(TAG,"----------Start----------------");
        Log.d(TAG, "| "+request.toString());
        String method=request.method();
        if("POST".equals(method)){
            StringBuilder sb = new StringBuilder();
            if (request.body() instanceof FormBody) {
                FormBody body = (FormBody) request.body();
                for (int i = 0; i < body.size(); i++) {
                    sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");
                }
                sb.delete(sb.length() - 1, sb.length());
                Log.d(TAG, "| RequestParams:{"+sb.toString()+"}");
            }
        }
        Log.d(TAG, "| Response:" + content);
        Log.d(TAG,"----------End:"+duration+"毫秒----------");
        return response.newBuilder()
                .body(ResponseBody.create(mediaType, content))
                .build();
    }
}
           

// 最後類名

OkhttpUtils.getInstance.call()