Using proxies with Google HTTP Client Library for Java

怎甘沉沦 提交于 2019-12-06 05:38:16

问题


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);
}

回答1:


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?



来源:https://stackoverflow.com/questions/14262519/using-proxies-with-google-http-client-library-for-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!