Connect through a Proxy : HttpURLConnection « Network Protocol « Java






Connect through a Proxy

    

import java.io.DataInputStream;
import java.io.FileOutputStream;
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 {
    byte[] b = new byte[1];
    Properties systemSettings = System.getProperties();
    systemSettings.put("http.proxyHost", "proxy.mydomain.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("mydomain\\MYUSER:MYPASSWORD".getBytes());
    con.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd);
    DataInputStream di = new DataInputStream(con.getInputStream());
    while (-1 != di.read(b, 0, 1)) {
      System.out.print(new String(b));
    }
  }
}

   
    
    
    
  








Related examples in the same category

1.Get the date of a url connection
2.Get the document expiration date
3.Get the document Last-modified date
4.Show the content type
5.Show the content length
6.Display request method
7.Get response code
8.Display response message
9.Display header information
10.Download and display the content
11.A Web Page Source Viewer
12.Reading from a URLConnection
13.Use BufferedReader to read content from a URL
14.Check if a page exists
15.Identify ourself to a proxy
16.Preventing Automatic Redirects in a HTTP Connection
17.Converting x-www-form-urlencoded Data
18.Getting the Cookies from an HTTP Connection
19.Sending a Cookie to an HTTP Server
20.Getting the Response Headers from an HTTP Connection
21.java.net.Authenticator can be used to send the credentials when needed
22.Grabbing a page using socket
23.Http Header Helper
24.Http connection Utilities
25.Available Port Finder