Skip to content

Instantly share code, notes, and snippets.

@vigack
Created November 22, 2017 01:41
Show Gist options
  • Save vigack/0a4ea17bf43b93044da32afbff16d7e5 to your computer and use it in GitHub Desktop.
Save vigack/0a4ea17bf43b93044da32afbff16d7e5 to your computer and use it in GitHub Desktop.
Java中使用网络代理
public class ProxyDemo {
@Test
public void test() throws IOException {
// 如果是http代理
//System.setProperty("http.proxyHost", sProxyHost);
//System.setProperty("http.proxyPort", sProxyPort)
System.setProperty("socksProxyHost", "127.0.0.1");
System.setProperty("socksProxyPort", "1080");
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("http://www.youtube.com").get().build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string()); // 正确打印出youtube的首页
}
}
@vigack
Copy link
Author

vigack commented Nov 22, 2017

如果不想硬编码,可以在JVM启动参数中设置,如:-DsocksProxyHost=127.0.0.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment