Java/Network Protocol/Proxy — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 07:21, 1 июня 2010
Detect Proxy Settings for Internet Connection
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
System.setProperty("java.net.useSystemProxies", "true");
List l = ProxySelector.getDefault().select(new URI("http://www.yahoo.ru/"));
for (Iterator iter = l.iterator(); iter.hasNext();) {
Proxy proxy = (Proxy) iter.next();
System.out.println("proxy hostname : " + proxy.type());
InetSocketAddress addr = (InetSocketAddress) proxy.address();
if (addr == null) {
System.out.println("No Proxy");
} else {
System.out.println("proxy hostname : " + addr.getHostName());
System.out.println("proxy port : " + addr.getPort());
}
}
}
}
Identify ourself to a proxy
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;
public class Main{
public static void main(String s[]) throws Exception{
try {
Properties systemSettings = System.getProperties();
systemSettings.put("proxySet", "true");
systemSettings.put("http.proxyHost", "proxy.mycompany.local");
systemSettings.put("http.proxyPort", "80");
URL u = new URL("http://www.java.ru");
HttpURLConnection con = (HttpURLConnection) u.openConnection();
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
String encodedUserPwd = encoder.encode("domain\\username:password".getBytes());
con.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd);
con.setRequestMethod("HEAD");
System.out.println(con.getResponseCode() + " : " + con.getResponseMessage());
System.out.println(con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (Exception e) {
e.printStackTrace();
System.out.println(false);
}
}
}
URL connection and proxy
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;
public class Main{
public static void main(String s[]) throws Exception{
try {
Properties systemSettings = System.getProperties();
systemSettings.put("proxySet", "true");
systemSettings.put("http.proxyHost", "proxy.mycompany.local");
systemSettings.put("http.proxyPort", "80");
URL u = new URL("http://www.java.ru");
HttpURLConnection con = (HttpURLConnection) u.openConnection();
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
String encodedUserPwd = encoder.encode("domain\\username:password".getBytes());
con.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd);
con.setRequestMethod("HEAD");
System.out.println(con.getResponseCode() + " : " + con.getResponseMessage());
System.out.println(con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (Exception e) {
e.printStackTrace();
System.out.println(false);
}
}
}