Okhttp3 简单单例封装

本文介绍了一个使用OkHttp的实用工具类,该类采用单例模式并支持GET和POST请求,通过示例展示了如何进行网络请求及响应处理,并利用日志拦截器记录请求和响应详情。
/**
 * 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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值