拦截器是一种强大的机制,可以监视、重写和重试调用.
拦截器的作用:
1.拦截器可以一次性对所有的请求和返回值进行修改。
2.拦截器可以一次性对请求的参数和返回的结果进行编码,比如统一设置为UTF-8.
3.拦截器可以对所有的请求做统一的日志记录,不需要在每个请求开始或者结束的位置都添加一个日志操作。
4.其他需要对请求和返回进行统一处理的需求....
OkHttp中拦截器分类
OkHttp中的拦截器分2个:
APP层面的拦截器(Application Interception)
Application Interceptor是在请求执行刚开始,还没有执行OkHttp的核心代码前进行拦截,Application拦截器的作用:
1、不需要担心是否影响OKHttp的请求策略和请求速度。
2、即使是从缓存中取数据,也会执行Application拦截器。
3、允许重试,即Chain.proceed()可以执行多次。(当然请不要盲目执行多次,需要加入你的逻辑判断)
网络请求层面的拦截器(Network Interception)
Network Interception是在连接网络之前
1、可以修改OkHttp框架自动添加的一些属性(当然最好不要修改)。
2、可以观察最终完整的请求参数(也就是最终服务器接收到的请求数据和熟悉)
---------------MainActivity---------------------------
package com.example.earl.mylanjieqi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = findViewById(R.id.bt1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//使用拦截器
OkHttpClient client = new OkHttpClient();
client.newBuilder().addInterceptor(new MyIntercepter());
Request re = new Request.Builder().url("http://www.baidu.com").build();
Call call = client.newCall(re);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String server = response.header("Server");
Log.d("TAG","--------"+server);
}
});
}
});
}
class MyIntercepter implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
//自己的逻辑
//如果访问的是百度改成八维
//获取请求头
Request request = chain.request();
String host = request.url().host();
if (host.equals("www.baidu.com")){
host="www.bawei.com";
}
//重新创建请求
Request build = request.newBuilder().url(host).build();
//让请求去执行
Response response = chain.proceed(build);
return response;
}
}
}
-------------Main2Activity---------------------
package com.example.earl.mylanjieqi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.IOException;
import java.util.HashMap;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class Main2Activity extends AppCompatActivity {
private EditText mobile;
private EditText password;
private Button login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mobile = findViewById(R.id.mobile);
password = findViewById(R.id.password);
login = findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String m = mobile.getText().toString();
String p = password.getText().toString();
Log.d("TAG","点击"+m+"-----"+p);
//请求网络
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new MyInterceptor1()).build();
Log.d("TAG","拦截器注册成");
FormBody formBody = new FormBody.Builder()
.add("mobile", m)
.add("password", p)
.build();
Request re = new Request.Builder().url("https://www.zhaoapi.cn/user/login").post(formBody).build();
//请求队列
Call call = okHttpClient.newCall(re);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("TAG","okhttp"+"成功-----");
}
});
}
});
}
class MyInterceptor1 implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
//获取请求体
Request request = chain.request();
RequestBody body = request.body();
Log.d("TAG","拦截器---"+body);
//获取手机号密码
HashMap<String, String> map = new HashMap<>();
if (body instanceof FormBody)
//取出
for (int i = 0; i <((FormBody)body).size() ; i++) {
String name=((FormBody)body).name(i);
String value=((FormBody)body).value(i);
//封装到Map
map.put(name,value);
}
//打印封装好的map
Log.d("TAG", "封装完毕--" + map.toString());
Response proceed = chain.proceed(request);
return proceed;
}
}
}
--------------activity_main------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/bt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮1"
/>
</LinearLayout>
-------------activity_main2-----------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Main2Activity">
<EditText
android:id="@+id/mobile"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登陆"/>
</LinearLayout>
网友评论