好吧,我一直在尝试在android上使用SOCKS代理。我太挣扎了,我没能正确使用它。
基本上我确实希望使用HttpURLConnection
通过SOCKS代理获取页面内容(必须)。
我使用的代码是:
String proxyHost = "192.168.2.2";
int proxyPort = 1999;
InetSocketAddress proxyAddr = new InetSocketAddress(proxyHost, proxyPort);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, proxyAddr);
URL request = new URL("http://requestb.in/sgjga5sg");
HttpURLConnection urlConnection = (HttpURLConnection) request.openConnection(proxy);
urlConnection.setDoInput(true);
urlConnection.setConnectTimeout(36000);
urlConnection.setReadTimeout(44000);
InputStream is = urlConnection.getInputStream();
for (int x = is.read(); x >= 0; x = is.read()) {
System.out.print((char) x);
}
System.out.println();
我得到SocketTimeOutException
,这是堆栈跟踪:
java.net.SocketTimeoutException
at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:37)
at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:237)
at java.net.PlainSocketImpl.socksReadReply(PlainSocketImpl.java:440)
at java.net.PlainSocketImpl.socksRequestConnection(PlainSocketImpl.java:340)
at java.net.PlainSocketImpl.socksConnect(PlainSocketImpl.java:326)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:181)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
at java.net.Socket.connect(Socket.java:887)
at com.android.okhttp.internal.Platform.connectSocket(Platform.java:174)
at com.android.okhttp.Connection.connect(Connection.java:152)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:332)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:199)
at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:25)
at com.guness.testsocks.MainActivity.doTheThing(MainActivity.java:81)
一些奇怪的事情:
Proxy.Type
更改为HTTP
并从互联网上选择合适的HttpProxy时,它可以正常工作,但我需要袜子。System.out.print
和循环,它是出于测试目的。编辑:
似乎SOCKS代理不能与android上的HttpURLConnection
一起使用。一些参考:
此thread和此thread声明如此。我想确定是否有办法不使用第三方库。
答案 0 :(得分:2)
我发现了问题,部分解决了。如我的问题所述,该设备为Lollipop(5.1.1)
。当我使用模拟器检查Marshmallow(6.0)
时,它的工作方式就像魅力一样,没有任何变化。 Lollipop
的模拟器检查也失败。
因此将来参考:
Android不支持在Marshmellow之前的设备上本机(using HURL)
使用socks代理。