gpt4 book ai didi

android - 如何从响应改造中检索 cookie,okhttp?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:53:05 24 4
gpt4 key购买 nike

我正在尝试从 API 响应中检索 Cookie 值,以在应用程序关闭时通过将 cookie 值设置为新的 API 调用来维护后端 session :

PostMan RestClient 对 API 调用的响应: enter image description here

RetrofitClient.java

public static Retrofit getClient() {

if (checkClient()) {
return getRetrofit();
}

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
CookieHandler cookieHandler = new CookieManager();

okhttp3.OkHttpClient client = new okhttp3.OkHttpClient.Builder().addNetworkInterceptor(interceptor)
.cookieJar(new JavaNetCookieJar(cookieHandler))
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();

Gson gson = new GsonBuilder()
.setLenient()
.create();

retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(client)
.build();
return retrofit;
}

API 调用

private void userLogin(String username, String password) {
Retrofit retrofit = RetrofitClient.getClient();

final LoginServices loginServices = retrofit.create(LoginServices.class);
Call<LoginResponse> call = loginServices.userLogin(username, password);

call.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
Log.d("Response code:", "===========" + response.code());

Log.d("==Cookie==1===", "==="+response.raw().request().headers().get("Cookie"));
Log.d("==Cookie==2==", "==="+response.headers().get("Cookie"));
Log.d("==Content-Type====", "==="+response.headers().get("Content-Type"));

}

@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
Log.e("TAG", "=======onFailure: " + t.toString());
t.printStackTrace();
// Log error here since request failed
}
});
}

日志:

Response code:: ===========200
==Cookie==1===: ===null
==Cookie==1===: ===null
==Content-Type====: ===application/json

我还尝试了其他各种方法,但它们对我不起作用。请帮忙!

最佳答案

List<String> Cookielist = response.headers().values("Set-Cookie");
String jsessionid = (Cookielist .get(0).split(";"))[0];

这对我有用,不是完美的解决方案,但它确实有效

关于android - 如何从响应改造中检索 cookie,okhttp?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48090485/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com