gpt4 book ai didi

android - 如何使用 Retrofit OkHttpClient 保持 session

转载 作者:太空宇宙 更新时间:2023-11-03 11:42:35 24 4
gpt4 key购买 nike

使用 DefaultHttpClient() 你可以做

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url_login.toURI());
HttpGet request1 = new HttpGet(url_getList.toURI());
HttpGet request2 = new HttpGet(url.getOtherList.toURI());
HttpResponse response = client.execute(request);
HttpResponse response1 = client.execute(request1);
HttpResponse response2 = client.execute(request2);

并且客户会保持 session ,我如何通过改造 2 管理以下内容

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();

// Customize the request
Request request = original.newBuilder()
.header("Accept", "application/json")
.header("Authorization", "auth-token")
.method(original.method(), original.body())
.build();

Response response = chain.proceed(request);

// Customize or return the response
return response;
}
}).build();

Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create());

Retrofit rt = builder.client(client).build();
RestAPI restAPI = rt.create(RestAPI.class);
....
callLogin = restAPI.login();
Call<Model> callModel = restAPI.getModel();

2 restApi 调用不起作用 restApi 客户端未登录

最佳答案

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

// init cookie manager
CookieHandler cookieHandler = new CookieManager();

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

Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create());

关于android - 如何使用 Retrofit OkHttpClient 保持 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36706795/

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