如何在 SignalR java 客户端中处理 set-cookie Header?

How to handle set-cookie Header in SignalR java Client?

我在 android 和 .net core3 中使用 SignalR java 客户端作为我的网络服务。 我在来自网络服务的响应中配置了 set-cookie header 以防止 DDOS attacks ,但现在我无法连接到我的集线器,因为 SignalR [=22] 中没有选项=] 客户端处理 set-cookie header 。 我该如何解决这个问题?

经过大量搜索,我得出了这个结论:

   hubConnection = HubConnectionBuilder.create(HUB_URL).withHandshakeResponseTimeout(60000).withHeaders(mapHeader).setHttpClientBuilderCallback(param1 -> {
                        param1.addInterceptor(new ApiClient.ReceivedCookiesInterceptor(G.context));
                        param1.addInterceptor(new ApiClient.AddCookiesInterceptor(G.context));
                    }).withTransport(TransportEnum.ALL).withAccessTokenProvider(Single.defer(() -> Single.just("An Access Token"))).build();

(setHttpClientBuilderCallback) 会给我一个配置生成器,我可以用它来处理来自响应的 setcookie

这是我的 ReceivedCookiesInterceptor:

 public static class ReceivedCookiesInterceptor implements Interceptor {
        private Context context;

        public ReceivedCookiesInterceptor(Context context) {
            this.context = context;
        }

        @Override
        public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            if (!originalResponse.headers("Set-Cookie").isEmpty()) {
                Log.i("HubLogin", "intercept: "+originalResponse.headers("Set-Cookie"));
                HashSet<String> cookies = (HashSet<String>) PreferenceManager.getDefaultSharedPreferences(context).getStringSet("PREF_COOKIES", new HashSet<String>());

                for (String header : originalResponse.headers("Set-Cookie")) {
                    cookies.add(header);
                }

                SharedPreferences.Editor memes = PreferenceManager.getDefaultSharedPreferences(context).edit();
                memes.putStringSet("PREF_COOKIES", cookies).apply();
                memes.apply();
            }

            return originalResponse;
        }
    }

这是我的 AddCookiesInterceptor:

public static class AddCookiesInterceptor implements Interceptor {
    public static final String PREF_COOKIES = "PREF_COOKIES";
    private Context context;
    public AddCookiesInterceptor(Context context ) {
        this.context = context;
    }

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

        HashSet<String> preferences = (HashSet<String>) PreferenceManager.getDefaultSharedPreferences(context).getStringSet(PREF_COOKIES, new HashSet<>());

        for (String cookie : preferences) {
            builder.addHeader("Cookie", cookie);
        }
        return chain.proceed(builder.build());
    }
}