OkHttp封裝攔截器
阿新 • • 發佈:2019-02-16
package com.lixinyang.mylanjiqi; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; 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 java.util.Map; importokhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = (Button) findViewById(R.id.btn); final EditText et_user = (EditText) findViewById(R.id.et_user); finalEditText et_pwd = (EditText) findViewById(R.id.et_pwd); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { OkHttpClient build = new OkHttpClient.Builder().addInterceptor(new MyIntentceptor()).build(); FormBody formBody = new FormBody.Builder() .add("mobile", et_user.getText().toString()) .add("password", et_pwd.getText().toString()) .build(); Request request = new Request.Builder().url("https://www.zhaoapi.cn/user/login").post(formBody).build(); Call call = build.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "請求失敗=====" ); } @Override public void onResponse(Call call, Response response) throws IOException { Log.e(TAG, "請求成功======" ); } }); } }); } class MyIntentceptor implements Interceptor{ @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); RequestBody body = request.body(); Log.e(TAG, "攔截器"+body ); Map<String,String> map = new HashMap<String,String>(); 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); Log.e(TAG, "電話號"+name+""+"密碼"+value ); map.put(name,value); } } Log.e(TAG, "封裝完畢---" ); Response response = chain.proceed(request); return response; } } }