Solved

URLConnection with Proxy & Domain

Posted on 2002-06-02
3
1,145 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Securing Jmx Console and web console 2 64
Java Options in Zimbra Server 2 44
Apps blocked by Java 9 55
Way to decrease size of apk file 9 40
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

932 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

11 Experts available now in Live!

Get 1:1 Help Now