按请求okhttp newbuilder
尝试以正确的方式实现OKHTTP。我了解必须共享OkhttpClient(Singleton),但是我不清楚.newBuilder();
示例代码:
// Instantiated once
private static OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(readTime, TimeUnit.MILLISECONDS)
.connectionPool(new ConnectionPool(200, connectTimeout, TimeUnit.MILLISECONDS));
.build();
public static String makeRestCall(String url, String data, Interceptor customInterceptor) {
// Questions on the line below
OkHttpClient newClient = client.newBuilder()
.addInterceptor(customInterceptor)
.build();
....
try (Response response = newClient.newCall(httpRequest).execute()) {
final ResponseBody body = response.body();
return body.string();
}
return "NO_DATA";
}
有一些问题
- 我在
.newbuilder()
时 > newclient ,原始
客户端
是否也通过参考更新? 类调用
MakerestCall
确定他们需要的自定义感应器。可以打电话.newbuilder()
为每个请求吗?
我一直在搜索文档并播放实施,但对上述情况并没有清楚。
任何援助/指针都将不胜感激。
Trying to implement okhttp the correct way. I understand the OkHttpClient must be shared (Singleton), however I am not clearly understanding .newBuilder();
Sample Code:
// Instantiated once
private static OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(readTime, TimeUnit.MILLISECONDS)
.connectionPool(new ConnectionPool(200, connectTimeout, TimeUnit.MILLISECONDS));
.build();
public static String makeRestCall(String url, String data, Interceptor customInterceptor) {
// Questions on the line below
OkHttpClient newClient = client.newBuilder()
.addInterceptor(customInterceptor)
.build();
....
try (Response response = newClient.newCall(httpRequest).execute()) {
final ResponseBody body = response.body();
return body.string();
}
return "NO_DATA";
}
I have a few questions around .newBuilder()
When we add a new interceptor to
newClient
, does the originalclient
also get updated by reference?Classes calling
makeRestCall
decide on what customInteceptor they need. Is it ok to call.newBuilder()
for every request?
I have been searching the documentation and playing with the implementation but haven't had clarity on the above.
Any assistance/pointers are appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,原件没有变化。它的配置是不可变的。
绝对地。该操作很便宜,因为它仅复制配置。没有复制资源密集型的内容,例如连接池和高速缓存。
No, the original is unchanged. Its configuration is immutable.
Absolutely. That operation is cheap because it only duplicates the configuration. Resource-intensive stuff like the connection pool and cache are not duplicated.