将代理与Google HTTP Client Library for Java结合使用 [英] Using proxies with Google HTTP Client Library for Java
问题描述
我使用Java的Google HTTP客户端库发出简单的JSON请求并解析响应.当我不通过代理时,它会很好地工作.但是现在我想允许我的用户在我的应用程序中使用代理(带有身份验证)功能.我查看了HttpTransport,HttpRequestFactory和HttpRequestInitializer类,但没有成功.
I use Google HTTP Client Library for Java to make simple JSON requests and parse responses. It works well when I don't go through a proxy. But now I'd like to allow my users to use a proxy (with authentication) functionality in my application. I looked in the HttpTransport, HttpRequestFactory and HttpRequestInitializer classes without any success.
到目前为止,我仅对示例进行了少量修改(并且大多数情况下,它正在删除不必要的代码).那么我在代码中的哪里添加代理设置?
I've only slightly modified the examples so far (and mostly it was removing unnecessary code). So where in the code do I add the proxy settings?
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
This seems to work just fine for an authenticated proxy using 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();
这还不足以满足您的需求吗?
Isn't this sufficient for your needs?
这篇关于将代理与Google HTTP Client Library for Java结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!