Using proxies with Google HTTP Client Library for Java
Asked Answered
T

1

7

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);
}
Tracay answered 10/1, 2013 at 16:24 Comment(3)
NetHttpTransport seems to be a wrapper for the built in java.net HTTP client... so I would guess that you could use the built in system properties to configure a proxy as discussed hereRoubaix
Hmmm... That's annoying. I would have hoped they used other libraries in a completely hidden way, not that some components of it are visible. I might switch to the Apache implementation then.Ceciliacecilio
Actually, it's impossible to get there with either Apache or java.net because the encapsulation doesn't care about setting the proxy authentication. I'll file a ticket.Ceciliacecilio
G
7

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?

Guarani answered 21/1, 2013 at 4:42 Comment(5)
No: I need to put a user name and a password in order to go through. This snippet doesn't give that option, sorry. Plus, this code is what I tried between my two first comments on my question.Ceciliacecilio
So you need to use credentials other than those of the system you are logged into?Guarani
Yes, my credentials are different on my system and on my proxy.Ceciliacecilio
OK, point me at the ticket you filed then so I can support it too.Guarani
Here you are: code.google.com/p/google-http-java-client/issues/detail?id=190Ceciliacecilio

© 2022 - 2024 — McMap. All rights reserved.