public static HttpProxySocketProvider connectViaProxy(String host,
int port,
String proxyHost,
int proxyPort,
String username,
String password,
String userAgent) throws UnknownHostException, IOException {
return connectViaProxy(host, port, proxyHost, proxyPort, null,
username, password, userAgent);
}
|
public static HttpProxySocketProvider connectViaProxy(String host,
int port,
String proxyHost,
int proxyPort,
String protocol,
String username,
String password,
String userAgent) throws UnknownHostException, IOException {
HttpProxySocketProvider socket = new HttpProxySocketProvider(host,
port, proxyHost, proxyPort);
int status;
String providerDetail;
try {
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
HttpRequest request = new HttpRequest();
if (protocol == null) {
protocol = "";
}
request.setHeaderBegin("CONNECT " + protocol + host + ":" + port +
" HTTP/1.0");
request.setHeaderField("User-Agent", userAgent);
request.setHeaderField("Pragma", "No-Cache");
request.setHeaderField("Proxy-Connection", "Keep-Alive");
out.write(request.toString().getBytes());
out.flush();
socket.responseHeader = new HttpResponse(in);
providerDetail = socket.responseHeader.getHeaderField("server");
if (socket.responseHeader.getStatus() == 407) {
String realm = socket.responseHeader.getAuthenticationRealm();
String method = socket.responseHeader.getAuthenticationMethod();
if (realm == null) {
realm = "";
}
if (method.equalsIgnoreCase("basic")) {
socket.close();
socket = new HttpProxySocketProvider(host, port, proxyHost,
proxyPort);
in = socket.getInputStream();
out = socket.getOutputStream();
request.setBasicAuthentication(username, password);
out.write(request.toString().getBytes());
out.flush();
socket.responseHeader = new HttpResponse(in);
} else if (method.equalsIgnoreCase("digest")) {
throw new IOException(
"Digest authentication is not supported");
} else {
throw new IOException("'" + method + "' is not supported");
}
}
status = socket.responseHeader.getStatus();
} catch (SocketException e) {
throw new SocketException("Error communicating with proxy server " +
proxyHost + ":" + proxyPort + " (" + e.getMessage() + ")");
}
if ((status < 200) || (status > 299)) {
throw new IOException("Proxy tunnel setup failed: " +
socket.responseHeader.getStartLine());
}
socket.providerDetail = providerDetail;
return socket;
}
|