Connecting to an Url using a Java program - Connecting through a proxy

0

The following code demonstartes how to connect to an url through a proxy . The code uses the default system proxy.


In case you want to use a different proxy than the default system proxy , you need to set the http.proxyHost and http.proxyPort
properties from your code using setProperty method of the System class ,
or you can provide the values as command line arguments when starting your java program , like
java -Dhttp.proxyHost=hostname -Dhttp.proxyPort=portNumber foo
, where foo is the name of the class . You may also create an instance of the Proxy class ,
and pass it to the openConnection() method of the URL class.



/** *PUBLIC SOFTWARE * *This source code has been placed in the public domain. You can use, modify, and distribute *the source code and executable programs based on the source code. * *However, note the following: * *DISCLAIMER OF WARRANTY * * This source code is provided "as is" and without warranties as to performance * or merchantability. The author and/or distributors of this source code may * have made statements about this source code. Any such statements do not constitute * warranties and shall not be relied on by the user in deciding whether to use * this source code.This source code is provided without any express or implied * warranties whatsoever. Because of the diversity of conditions and hardware * under which this source code may be used, no warranty of fitness for a * particular purpose is offered. The user is advised to test the source code * thoroughly before relying on it. The user must assume the entire risk of * using the source code. * */ import java.io.*; import java.net.*; import com.sun.org.apache.xml.internal.security.utils.Base64; /** * * @author amal * version 1.0 */ public class UrlConA { public static void main(String[] args) { System.setProperty("java.net.useSystemProxies", "true"); BufferedReader in = null; try { URL url = new URL("http://www.w3schools.com"); URLConnection uc = url.openConnection(); String encoded = new String(Base64.encode(new String( "username:password").getBytes())); uc.setRequestProperty("Proxy-Authorization", "Basic " + encoded); uc.connect(); in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null != in) { in.close(); } } catch (IOException e) { // ignore } } } }

Read more »

0 comments:

Post a Comment

© Zone817. Powered by Blogger.