Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OkHTTPClient Proxy authentication how to?

Question: How do I add a authorization proxy to OkHTTP.

I know that OkHTTP's builder does support proxies although I am having a hard time setting one up.

/**
 * Given a Url and a base64 encoded password return the contents of a website.
 * @param urlString
 * @param password
 * @return JSON
 */
public String getURLJson(String urlString, String password) {       
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();

        Request request = new Request.Builder()
          .url(urlString)
          .get()
          .addHeader("authorization", "Basic " + password)
          .addHeader("cache-control", "no-cache")
          .build();

        Response response = null;
        try {
            response = client.newCall(request).execute();
            String string = response.body().string();
            response.body().close();
            return string;
        } catch (IOException e) {
            System.err.println("Failed scraping");
            e.printStackTrace();
        }
        return "failed";
    }

I have the IP / port / username / password.

Although I do not know how to turn those into a Proxy proxy which can then be used in client.SetProxy().

It seems overly complicated and I simply can't seem to figure it out. Any help would be appreciated.

like image 691
Liably Avatar asked Feb 22 '16 12:02

Liably


People also ask

How do I add a proxy to okHttp?

You can set the proxy that the JVM uses, with the flags (e.g.) java -Dhttp. proxyHost=10.0. 0.100 -Dhttp. proxyPort=8800 myclass (Useful for when okHttp change their api AGAIN).


1 Answers

Try this:

int proxyPort = 8080;
String proxyHost = "proxyHost";
final String username = "username";
final String password = "password";

Authenticator proxyAuthenticator = new Authenticator() {
  @Override public Request authenticate(Route route, Response response) throws IOException {
       String credential = Credentials.basic(username, password);
       return response.request().newBuilder()
           .header("Proxy-Authorization", credential)
           .build();
  }
};

OkHttpClient client = new OkHttpClient.Builder()
    .connectTimeout(60, TimeUnit.SECONDS)
    .writeTimeout(60, TimeUnit.SECONDS)
    .readTimeout(60, TimeUnit.SECONDS)
    .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)))
    .proxyAuthenticator(proxyAuthenticator)
    .build();
like image 183
Jesse Wilson Avatar answered Oct 13 '22 19:10

Jesse Wilson