Solved

URLConnection with Proxy & Domain

Posted on 2002-06-02
3
1,144 Views
Last Modified: 2011-09-20
Hai ..  

I try to use this function but my pc not join to any domain and using proxy server to connect to internet ..

i try this .. function

the problem is .. i need pass DOMAIN name to connect to internet ...

please give me advice .. thank .


// The Authenticator class ******************************
import java.io.*;
import java.net.*;

public class URLAuthenticator {
 /**
  * The alphabet dictionary used for encoding
  */
 public static final char [ ]  alphabet = {
 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',   //  0 to  7
 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',   //  8 to 15
 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',   // 16 to 23
 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',   // 24 to 31
 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',   // 32 to 39
 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',   // 40 to 47
 'w', 'x', 'y', 'z', '0', '1', '2', '3',   // 48 to 55
 '4', '5', '6', '7', '8', '9', '+', '/' }; // 56 to 63

 /**
  * Encode a string
  * @param s the string to encode
  * @return the encoded string
  */
 public static String encode(String s) {
   return encode(s.getBytes());
 }

 /**
  * Encode a byte[] array
  * @param octetString the byte[] buffer to encode
  * @return the encoded string
  */
 public static String encode(byte[] octetString) {
   int  bits24;
   int  bits6;
   char[] out = new char[((octetString.length - 1) / 3 + 1) * 4];
   int outIndex = 0;
   int i = 0;
   while ((i + 3) <= octetString.length) {
     // store the octets
     bits24 = (octetString[i++] & 0xFF ) << 16;
     bits24 |= (octetString[i++] & 0xFF ) << 8;
     bits24 |= (octetString[i++] & 0xFF ) << 0;
     bits6 = (bits24 & 0x00FC0000) >> 18;
     out[outIndex++] = alphabet[bits6];
     bits6 = (bits24 & 0x0003F000) >> 12;
     out[outIndex++] = alphabet[bits6];
     bits6 = (bits24 & 0x00000FC0) >> 6;
     out[outIndex++] = alphabet[bits6];
     bits6 = (bits24 & 0x0000003F);
     out[outIndex++] = alphabet[bits6];
   }
   if (octetString.length - i == 2) {
     // store the octets
     bits24 = (octetString[i] & 0xFF ) << 16;
     bits24 |= (octetString[i + 1] & 0xFF) << 8;
     bits6 = (bits24 & 0x00FC0000) >> 18;
     out[outIndex++] = alphabet[bits6];
     bits6 = (bits24 & 0x0003F000) >> 12;
     out[outIndex++] = alphabet[bits6];
     bits6 = (bits24 & 0x00000FC0) >> 6;
     out[outIndex++] = alphabet[bits6];
     // padding
     out[outIndex++] = '=';
   } else if (octetString.length - i == 1) {
     // store the octets
     bits24 = (octetString[i] & 0xFF) << 16;
     bits6 = (bits24 & 0x00FC0000) >> 18;
     out[outIndex++] = alphabet[bits6];
     bits6 = (bits24 & 0x0003F000) >> 12;
     out[outIndex++] = alphabet[bits6];
     // padding
     out[outIndex++] = '=';
     out[outIndex++] = '=';
   }
   return new String(out);
 }

 
public static void authenticate(URLConnection uc, String user, String password) {
    String encoding = encode((user + ":" + password).getBytes());
    uc.setRequestProperty("Authorization", "Basic " + encoding);
}

 /**
  * Create an authenticated URLConnection
  * @param u the URL to open the connection from
  * @param user the users name
  * @param password the users password
  * @return the authenticated URLConnection
  */
 public static URLConnection openConnection(URL u, String user, String password) {
   URLConnection result = null;
   try {
     result = u.openConnection();
     if (result != null) {
       authenticate(result, user, password);
     }
   } catch (Exception ex) {
     ex.printStackTrace();
   }
   return result;
 }

 /**
  * Get a URL content object through an authenticated URLConnection
  * @param u the URL to get the content from
  * @param user the users name
  * @param password the users password
  * @return the content of the URL
  */
 public static Object getContent(URL u, String user, String password) {
   Object result = null;

   try {
     URLConnection uc = openConnection(u, user, password);
     if (uc != null) {
       result = uc.getContent();
     }
   } catch (Exception ex) {
     ex.printStackTrace();
   }
   return result;
 }

 /**
  * Get a URL InputStream object through an authenticated URLConnection
  * @param u the URL to get the InputStream object from
  * @param user the users name
  * @param password the users password
  * @return the InputStream object of the URL
  */
 public static InputStream openStream(URL u, String user, String password) {
   InputStream result = null;
   try {
     URLConnection uc = openConnection(u, user, password);
     if (uc != null) {
     result = uc.getInputStream();
   }
   } catch (Exception ex) {
     ex.printStackTrace();
   }
   return result;
 }

 public static void main(String args[])throws Exception {
   URL loader = null;
   String line = "";
   
   System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");
   
   System.setProperty("proxyHost", "10.8.0.6");
   System.setProperty("proxyPort", "80");
   
   try {
     loader = new URL("http://www.yahoo.com.sg");
   } catch(MalformedURLException mue) {
     System.out.println("Invalid URL !");
   }
   try {
     URLConnection con = URLAuthenticator.openConnection(loader, user_name, password);
     
   new InputStreamReader(con.getInputStream());
     
     BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
     while ((line = br.readLine()) != null)
       if(line!=null)
       System.out.println(line);
     br.close();
   
   }
   catch(IOException e) {
      e.printStackTrace();
   }
 
 }

}
0
Comment
Question by:jbrizal
3 Comments
 
LVL 2

Accepted Solution

by:
userquin earned 200 total points
ID: 7053513
Hi:

I suggest you implementing your own Authenticator (extends from java.net.Autheticator class). Then invoking java.net.Authenticator.setDefault(new MyOwnAuthenticator()). When you invoke URLConnection.getInputStream method, MyOwnAuthenticator.getPasswordAuthentication() will be called from underling HttpURLConnection (in JKD 1.2/1.3/1.4). Then you can ask the client for user and password for PROXY or REALM authentication.

For example:

public class MyOwnAuthenticator extends java.net.Authenticator {

// Constructors and any other methods ....
...
...
  protected synchronized PasswordAuthentication getPasswordAuthentication() {

    final InetAddress ia = getRequestingSite();
    String host = null;
    if(ia != null) host = ia.getHostName();

    // Here I show a Dialog showing client host and realm from where is requesting authentication
    dialog = new Dialog(owner, host, getRequestingPrompt());

    showDialog();

    return new PasswordAuthentication(dialog.getUser(), dialog.getPassword());
  }

// some other methods ...
...
...
}

My Dialog returns user and password for realm or proxy authentication.

Then in other class you must invoke this line:

java.net.Authenticator.setDefault(new MyOwnAuthenticator());

Sometimes, your applications have a Authenticator set by default, such as Java Web Start (JWS) or Java Applet under Java 1.2/1.3/1.4 Plugin. If you are using JDK 1.2 or 1.3 you cannot overwrite this default authenticator via setDefault method. Under JDK 1.4 you can overwrite it using setDefault method.

To avoid this under JDK 1.2 or 1.3 you can use this lines of code:

    try {
      Class clazz = Class.forName("java.net.Authenticator");
      Field auth = clazz.getDeclaredField("theAuthenticator");
      auth.setAccessible(true);
      auth.set(null, new MyOwnAuthenticator());
    } catch (Throwable t) {
      Authenticator.setDefault(new MyOwnAuthenticator());
    }

You must create your own dialog.

Hope this help.

Bye.

Joaquín.
0
 
LVL 35

Expert Comment

by:girionis
ID: 8813860
No comment has been added lately, so it's time to clean up this TA.

I will leave a recommendation in the Cleanup topic area that this question is:

- points to userquin

Please leave any comments here within the
next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER !

girionis
Cleanup Volunteer
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This video teaches viewers about errors in exception handling.

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now