HttpURLConnection proxy

In this chapter you will learn:

  1. Identify ourself to a proxy

Identify ourself to a proxy

The following code creates a Properties and sets the proxy information.

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;
/*from j  ava 2 s  . co m*/
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);
  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use Authenticator with HttpURLConnection
  2. Accessing a Password-Protected URL
Home » Java Tutorial » URL URI
URL
URL Creation
URL for jar file
URL Components
Convert file path to URL
URL Relative
URL Protocol
Read from URL
Compare URL
URLConnection
HTTP Header
URLConnection Post
Cookie
URLConnection Read
HttpURLConnection
HttpURLConnection Properties
HttpURLConnection proxy
HttpURLConnection Authenticator
HTTPS
JarURLConnection
Encode a URL
Decode a URL
URI
URI Normalization
URI Resolution
URI Relativization
Convert URI to URL
IP Address
IP Ping
NetworkInterface