Linjiajia
2023-04-24 fcdddf8b9b34f9930bec454b5fffe41c0e33ba3c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.android.app_base.http.interceptor;
 
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
 
import com.android.app_base.base.BaseConfig;
import com.android.app_base.manager.AppManager;
import com.android.app_base.manager.UserManager;
import com.blankj.utilcode.util.ToastUtils;
 
import org.json.JSONException;
import org.json.JSONObject;
 
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
 
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okio.Buffer;
import okio.BufferedSource;
 
/**
 * @author Ljj
 * @date 2023.04.07. 19:53
 * @desc
 */
public class AuthInterceptor implements Interceptor {
 
    private Context context;
    public AuthInterceptor() {
    }
 
    public AuthInterceptor(Context context) {
        this.context = context;
    }
 
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
 
        // Add Authorization header to the request
        Request.Builder builder = originalRequest.newBuilder();
        //添加头部token
        String token = UserManager.getInstance().getToken();
        if (!TextUtils.isEmpty(token)) {
            builder.addHeader("Authorization", token);
        }
 
        Request newRequest = builder.build();
        Response response = chain.proceed(newRequest);
        // 处理API返回的数据状态码
        try {
            BufferedSource source = response.body().source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.getBuffer();
            Charset UTF8 = StandardCharsets.UTF_8;
            String string = buffer.clone().readString(UTF8);
            JSONObject responseObject = new JSONObject(string);
            int code = responseObject.getInt("code");
            if (code == BaseConfig.TOKEN_INVALID ) {
                UserManager.getInstance().clearToken();
                AppManager.getAppManager().finishAllActivity();
                AppManager.getAppManager().startActivityForName(BaseConfig.LOGIN_ACTIVITY);
                throw new IOException("登录状态失效,请重新登录");
            }
        } catch (JSONException e) {
            // 处理JSON解析异常
            // ...
        }
 
        return response;
    }
}