public class LoggingInterceptor implements okhttp3.Interceptor { public static String TAG = "LogInterceptor"; @Override public Response intercept(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(); } }public class NetRequestData { public static void call(String url, Map<String,String> params, final Callbak callbak){ OkHttpClient client=new OkHttpClient.Builder() .addInterceptor(new LoggingInterceptor()) .build(); FormBody.Builder body= new FormBody.Builder(); for (Map.Entry<String, String> stringStringEntry : params.entrySet()) { body.add(stringStringEntry.getKey(),stringStringEntry.getValue()); } RequestBody build = body.build(); Request request=new Request.Builder().url(url).header("User-Agent", "OkHttp Example").post(build).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { callbak.RequestFaliure(call,e); } @Override public void onResponse(Call call, Response response) throws IOException { callbak.RequestSuccess(call,response); } }); }
okhttp拦截器的实现
最新推荐文章于 2023-06-19 17:42:02 发布