我正在开发一个将使用代理与服务器建立连接的应用。
为此,我正在执行一些测试!
为了验证,我做了以下测试:
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import static junit.framework.Assert.assertTrue;
@RunWith(AndroidJUnit4.class)
public class OkHttpClientTest {
private static int PORT = 1080;
private static String[] IPS = {"127.0.0.10", "127.0.0.11","127.0.0.12"};
private static String USER_NAME = "USUARIO";
private static String PASSWORD = "SENHA";
private static String URL_CONNECT = "https://www.google.com/";
private final Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(USER_NAME, PASSWORD.toCharArray());
}
};
@Test
public void testSocksFunctionality() throws IOException {
// set Authenticator
Authenticator.setDefault(authenticator);
// Create socket...
final Socket socket = new Socket(IPS[0], PORT);
assertTrue(socket.isConnected());
//create URL...
final URL url = new URL(URL_CONNECT);
InetSocketAddress socketAddress = new InetSocketAddress(IPS[0], PORT);
// create Proxy
final Proxy proxy = new Proxy( Proxy.Type.SOCKS, socketAddress );
// Open connection...
final URLConnection urlConnection = url.openConnection(proxy);
urlConnection.connect();
assertTrue( urlConnection.getDoInput() );
final OkHttpClient client = new OkHttpClient.Builder()
.proxy(proxy)
.retryOnConnectionFailure(false)
.build();
final Request request = new Request.Builder()
.url(URL_CONNECT)
.build();
assertTrue(client.newCall(request).execute().isSuccessful());
}
}
这将使用代理测试连接。
当我在24以下的API上运行测试时,会发生以下错误:
java.net.UnknownHostException: Host is unresolved: www.google.com
at java.net.Socket.connect(Socket.java:865)
at okhttp3.internal.platform.AndroidPlatform.connectSocket(AndroidPlatform.java:63)
at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:223)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:149)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:192)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:121)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:100)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
当我删除代理时,它可以正常工作!
如何在API 24以下的版本中使用代理建立连接?