Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A connection factory for using OkHttp with Kevin Sawicki's HttpRequest library.
/**
* A {@link HttpRequest.ConnectionFactory connection factory} which uses OkHttp.
* <p/>
* Call {@link HttpRequest#setConnectionFactory(HttpRequest.ConnectionFactory)} with an instance of
* this class to enable.
*/
public class OkConnectionFactory implements HttpRequest.ConnectionFactory {
private final OkHttpClient client;
public OkConnectionFactory() {
this(new OkHttpClient());
}
public OkConnectionFactory(OkHttpClient client) {
if (client == null) {
throw new NullPointerException("Client must not be null.");
}
this.client = client;
}
public HttpURLConnection create(URL url) throws IOException {
return client.open(url);
}
public HttpURLConnection create(URL url, Proxy proxy) throws IOException {
throw new UnsupportedOperationException(
"Per-connection proxy is not supported. Use OkHttpClient's setProxy instead.");
}
}
@kevinsawicki

This comment has been minimized.

Copy link

kevinsawicki commented Jun 20, 2013

👉🆒👈

@rockerhieu

This comment has been minimized.

Copy link

rockerhieu commented Jul 2, 2014

🆒

And here is how I integrated with OkHttp 2.0:

/**
 * A {@link HttpRequest.ConnectionFactory connection factory} which uses OkHttp.
 * <p/>
 * Call {@link HttpRequest#setConnectionFactory(HttpRequest.ConnectionFactory)} with an instance of
 * this class to enable.
 */
public class OkConnectionFactory implements HttpRequest.ConnectionFactory {

  private final OkHttpClient client;

  private final OkUrlFactory factory;

  public OkConnectionFactory() {
    this(new OkHttpClient());
  }

  public OkConnectionFactory(OkHttpClient client) {
    if (client == null) {
      throw new NullPointerException("Client must not be null.");
    }
    this.client = client;
    factory = new OkUrlFactory(client);
  }

  public HttpURLConnection create(URL url) throws IOException {
    return factory.open(url);
  }

  public HttpURLConnection create(URL url, Proxy proxy) throws IOException {
    throw new UnsupportedOperationException(
        "Per-connection proxy is not supported. Use OkHttpClient's setProxy instead.");
  }
}
@davidbilly

This comment has been minimized.

Copy link

davidbilly commented Nov 13, 2014

@rockerhieu I can't import the OkUrlFactory class, where i can find it? By the way i using the okhttp 2.1.0.

thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.