Last active
August 29, 2015 14:13
-
-
Save agatti/7620010f1a356965e4d7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.squareup.okhttp.OkHttpClient; | |
import com.squareup.okhttp.Request; | |
import com.squareup.okhttp.Response; | |
import java.io.IOException; | |
import java.net.*; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class ProxyTest { | |
private static class CustomProxySelector extends ProxySelector { | |
private final List<Proxy> proxies = new ArrayList<>(); | |
public CustomProxySelector() { | |
proxies.add(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8080))); | |
} | |
@Override | |
public List<Proxy> select(URI uri) { | |
return proxies; | |
} | |
@Override | |
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { | |
throw new RuntimeException("CONNECTION FAILED"); | |
} | |
} | |
public static void main(final String... arguments) throws Exception { | |
CustomProxySelector selector = new CustomProxySelector(); | |
ProxySelector.setDefault(selector); | |
URL url = new URL("http://www.example.com/"); | |
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); | |
connection.connect(); | |
ByteString byteString = Okio.buffer(Okio.source(connection.getInputStream())).readByteString(); | |
System.out.printf("HttpURLConnection response:%n%s%n", byteString.utf8()); | |
OkHttpClient client = new OkHttpClient(); | |
Request request = new Request.Builder().url(url).build(); | |
Response response = client.newCall(request).execute(); | |
System.out.printf("OkHttpClient response:%n%s%n", response.body().string()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment