我使用 Google HTTP Client Library for Java 发出简单的 JSON 请求并解析响应。当我不通过代理时它效果很好。但现在我想允许我的用户在我的应用程序中使用代理(带有身份验证)功能。我查看了 HttpTransport、HttpRequestFactory 和 HttpRequestInitializer 类,但没有成功。
到目前为止,我只稍微修改了示例(主要是删除了不必要的代码)。那么我应该在代码中的哪里添加代理设置呢?
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
static final JsonFactory JSON_FACTORY = new JacksonFactory();
<T> T get(String url, Class<T> type) throws IOException {
HttpRequestFactory requestFactory =
HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) {
request.setParser(new JsonObjectParser(JSON_FACTORY));
}
});
HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(url));
return request.execute().parseAs(type);
}
对于使用 google-http-client:1.13.1-beta 的经过身份验证的代理来说,这似乎工作得很好
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, PROXY_PORT));
HttpTransport httpTransport = new NetHttpTransport.Builder().setProxy(proxy).build();
这还不足以满足您的需求吗?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)