oleg 的回答当然是正确的,我只是想把信息直接放在这里,以防链接坏了。在创建 HttpClient 的代码中,我使用此代码让它使用我的套接字工厂:
CustomSocketFactory socketFactory = new CustomSocketFactory();
Scheme scheme = new Scheme("http", 80, socketFactory);
httpclient.getConnectionManager().getSchemeRegistry().register(scheme);
CustomSocketFactory
是我自己的套接字工厂,我想将它用于正常的 HTTP 流量,这就是我使用"http"
and80
作为参数的原因。
我的 CustomSchemeSocketFactory 看起来与此类似:
public class CustomSchemeSocketFactory implements SchemeSocketFactory {
@Override
public Socket connectSocket( Socket socket, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpParams params ) throws IOException, UnknownHostException, ConnectTimeoutException {
if (localAddress != null) {
socket.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
socket.bind(localAddress);
}
int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
int soTimeout = HttpConnectionParams.getSoTimeout(params);
try {
socket.setSoTimeout(soTimeout);
socket.connect(remoteAddress, connTimeout );
} catch (SocketTimeoutException ex) {
throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out");
}
return socket;
}
@Override
public Socket createSocket( HttpParams params ) throws IOException {
// create my own socket and return it
}
@Override
public boolean isSecure( Socket socket ) throws IllegalArgumentException {
return false;
}
}