Use proxy to do a http connection in Java
Description
The following code shows how to use proxy to do a http connection.
Example
/*from www . j av a2s .c o m*/
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;
import sun.misc.BASE64Encoder;
public class Main {
public static void main(String[] argv) throws Exception {
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.google.com");
HttpURLConnection con = (HttpURLConnection) u.openConnection();
BASE64Encoder encoder = new 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);
}
}
The code above generates the following result.