How to use a proxy with Java and OkHttp

In today's post, we are going to discuss how you can use a proxy, in particular a GridPanel mobile proxy, in Java utilising the OkHttp library from Square. OkHttp is a great HTTP client for Java which makes things efficient for you by default. If you need to learn more about mobile proxies, in particular, what they are and how they work, you can read our post explaining just that. 

Prerequisites

Before we begin let's make sure that you have the following:

  1. Mobile proxy details, if you need some you can grab a GridPanel mobile proxy from our dashboard.
  2. A Java environment setup using your favorite editor of choice.
  3. OkHttp library is installed and functioning correctly.

Setting up the proxy

First things first, you need to set up your proxy for use with OkHttp. To do so you need to create a Proxy object and pass in the relevant connection information. You can see an example of how to do this here:

public class MobileProxyExample {
  public static void main(String[] args) throws Exception {
    String proxyHost = "your-proxy-host";
    int proxyPort = 12345;

    Proxy proxy = new Proxy(
      Proxy.Type.HTTP,
      new InetSocketAddress(proxyHost, proxyPort)
    );

  }
}

If your proxy requires authentication, we will come to that a bit later in the article.

Making the HTTP request

Great, so now we have our Proxy object set up, we can make our first HTTP, routing it via our mobile proxy. In this example, we are going to request https://example com and we can do this as follows:

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MobileProxyExample {

  public static void main(String[] args) throws Exception {
    String proxyHost = "your-proxy-host";
    int proxyPort = 12345;

    Proxy proxy = new Proxy(
      Proxy.Type.HTTP,
      new InetSocketAddress(proxyHost, proxyPort)
    );

    OkHttpClient client = new OkHttpClient.Builder().proxy(proxy).build();

    Request request = new Request.Builder().url("https://example.com").build();

    try (Response response = client.newCall(request).execute()) {
      System.out.println(response.body().string());
    }
  }
}

As you can see above, we have added the necessary code to create an OkHttp client, configured with our proxy. We can then use this client to make an HTTP request to example.com and read the response body. Please note that we had to add the correct import statements at the top of the file to ensure we can access OkHttp.

Adding proxy authentication

If your proxy requires authentication via username/password then we can make a slight modification to the above code to make this work.

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MobileProxyExample {

  public static void main(String[] args) throws Exception {
    String proxyHost = "your-proxy-host";
    int proxyPort = 12345;
    String username = "username";
    String password = "password";

    Proxy proxy = new Proxy(
      Proxy.Type.HTTP,
      new InetSocketAddress(proxyHost, proxyPort)
    );

    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()
      .proxy(proxy)
      .proxyAuthenticator(proxyAuthenticator)
      .build();

    Request request = new Request.Builder().url("https://example.com").build();

    try (Response response = client.newCall(request).execute()) {
      System.out.println(response.body().string());
    }
  }
}

We have introduced a new variable "proxyAuthenticator" which takes our username and password to support proxy authentication. We then need to ensure that we pass this to the OkHttp client build phase so that all our requests with this client use our authenticated mobile proxy.

Conclusion

Using a proxy in Java can be a powerful tool for accessing external resources and improving performance.

By understanding how to use the OkHttp library and passing in the appropriate proxy server information, you can easily make requests through a proxy in your Java applications.

Sign up for an account and join our grid today to keep you ahead of your competitors.