您的位置:首页 > 理论基础 > 计算机网络

关于OKhttp的拦截器

2017-09-21 14:43 183 查看

写在前面:本篇博客并没有太多可说的,就是一片简简单单的Okhttp拦截器

activity_main布局:

<Button
android:id="@+id/interceptor"
android:text="okhttp应用程序拦截器"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>

<Button
android:id="@+id/interceptorNetWork"
android:text="okhttp网络拦截器"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"/>

一个CacheInerceptor的类:

public class CacheInerceptor implements Interceptor {

@Override
public Response intercept(Chain chain) throws IOException {

// 得到 Response 对象
Response response = chain.proceed(chain.request());

return response.newBuilder()
// 设置缓存标签,以及60秒的时长
.header("Cache-Control", "max-age=60")
.build();

}
}

MainActivity:

/**
* okhttp 底层网络请求使用的是 Socket,长连接
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private String Path = "http://publicobject.com/helloworld.txt";
private Button mInterceptor;
private Button mInterceptorNetWork;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

initView();

}

public void initView() {

mInterceptor = (Button) findViewById(R.id.interceptor);
mInterceptorNetWork = (Button) findViewById(R.id.interceptorNetWork);

mInterceptor.setOnClickListener(this);
mInte
4000
rceptorNetWork.setOnClickListener(this);
}

@Override
public void onClick(View view) {

switch (view.getId()) {

case R.id.interceptor:

interceptor();

break;
case R.id.interceptorNetWork:

interceptorNetWork();
break;

default:
break;

}

}

public void interceptor() {

new Thread() {
@Override
public void run() {
super.run();
try {
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new LoggingInterceptor()).build();

Request request = new Request.Builder().url(Path).build();

Response response = client.newCall(request).execute();

String string = response.body().string();

Log.e("GHQ", string);

} catch (Exception e) {
e.printStackTrace();
}
}
}.start();

}

/**
* 日志拦截器:请求来的时候 先在此处处理,就可以得到发请求到得到请求消耗了多长时间
* 排查网络请求速度慢的根本原因:
* <p>
* 1. 可能网络不给力
* 2. 可能是服务端出现问题(逻辑代码,硬件)
* 3.
*/
class LoggingInterceptor implements Interceptor {

@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();

long t1 = System.nanoTime();

System.out.println(" request  = " + String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);

long t2 = System.nanoTime();

//得出请求网络,到得到结果,中间消耗了多长时间
System.out.println("response  " + String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
}

/**
* 压缩拦截器:压缩你请求的内容,以及服务器的支持
* http1.1默认进行压缩
*/

class GzipRequestInterceptor implements Interceptor {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request originalRequest = chain.request();
if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
return chain.proceed(originalRequest);
}

Request compressedRequest = originalRequest.newBuilder()
.header("Content-Encoding", "gzip")
.method(originalRequest.method(), gzip(originalRequest.body()))
.build();
return chain.proceed(compressedRequest);
}

private RequestBody gzip(final RequestBody body) {
return new RequestBody() {
@Override
public MediaType contentType() {
return body.contentType();
}

@Override
public long contentLength() {
return -1; // We don't know the compressed length in advance!
}

@Override
public void writeTo(BufferedSink sink) throws IOException {
BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
body.writeTo(gzipSink);
gzipSink.close();
}
};
}
}

public void interceptorNetWork() {

new Thread() {

@Override
public void run() {
super.run();
try {

OkHttpClient client = new OkHttpClient.Builder().addNetworkInterceptor(new CacheInerceptor()).build();

Request request = new Request.Builder().url(Path).build();

Response response = null;

response = client.newCall(request).execute();

String string = response.body().string();

Log.d("GHQ",string);
} catch (IOException e) {
e.printStackTrace();
}

}
}.start();

}
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Okhttp拦截器