gpt4 book ai didi

android - 与 Retrofit 2 并行执行 http 请求

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:22:16 25 4
gpt4 key购买 nike

我想在 Retrofit 2 中实现多个并行请求。我有以下结构来提出 3 个请求:

HistoricalRApi.IStockChart service=HistoricalRApi.getMyApiService();
//^BVSP,^DJI,^IXIC
Call<HistoricalDataResponseTimestamp> call1= service.get1DHistoricalDataByStock("^IXIC");
Call<HistoricalDataResponseTimestamp> call2= service.get1DHistoricalDataByStock("^DJI");
Call<HistoricalDataResponseTimestamp> call3= service.get1DHistoricalDataByStock("^GSPC");
call1.enqueue(retrofitCallbackAmerica());
call2.enqueue(retrofitCallbackAmerica());
call3.enqueue(retrofitCallbackAmerica());
}

我在 Retrofit1 中读到过,在定义其余适配器时,可以使用 .setExecutor 定义并行请求,如下所示:

RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(END_POINT)
.setLogLevel(RestAdapter.LogLevel.FULL)
.setExecutors(Executors.newFixedThreadPool(3), null)
.build();

我的问题是如何在 Retrofit 2 中实现同样的效果?提前致谢

最佳答案

感谢 Colin Gillespie 链接,我已经实现了 Jake Wharton 所说的,结果如下:

 public static IStockChart getMyApiService() {
OkHttpClient client=new OkHttpClient();
Dispatcher dispatcher=new Dispatcher();
dispatcher.setMaxRequests(3);
client.setDispatcher(dispatcher);
// OkHttpClient client = new OkHttpClient();
// HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
// interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// client.interceptors().add(interceptor);
if(myService ==null){
Retrofit retrofit=new Retrofit.Builder()
.baseUrl("http://chartapi.finance.yahoo.com/")
.addConverterFactory(JsonpGsonConverterFactory.create())
.client(client)
.build();
myService=retrofit.create(IStockChart.class);
return myService;
} else {
return myService;
}



}

关于android - 与 Retrofit 2 并行执行 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35012030/

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