Java sockets-Using a proxy server

Source: Internet
Author: User
Tags ftp access

Why use a proxy server does not need to say more.

Use proxy

Java provides a proxy class implementation to communicate using proxies.

constructor proxy for the proxy class (Proxy.type type, socketaddress sa). Where type represents the proxy type, there are three proxy types: DIRECT (which means no proxy is used), HTTP (which means using advanced protocol proxies such as HTTP or FTP), SOCKETS (representing the use of the SOCKETS proxy). The SA represents the proxy address.

Once the proxy object is created, the program can either use URLConnection to open the connection, or create a proxy object to use for this connection when creating a socket connection.

Where the URL provides a urlconnection openconnection (proxy proxy), the socket provides a socket (proxy) constructor.

Use the URL's openconnection as an example:

 Public Static voidHttpproxy ()throwsIOException {//Proxy ObjectProxy proxy =NewProxy (Proxy.Type.HTTP,Newinetsocketaddress (IP, PORT)); //addresses that need to be accessedString urlstr = "http://www.zhyea.com"; //Create a connectionURL url =NewURL (URLSTR); URLConnection Conn=url.openconnection (proxy); //Output Access Results        Try{Scanner Scan=NewScanner (Conn.getinputstream ()); StringBuilder Builder=NewStringBuilder ();  while(Scan.hasnextline ()) {Builder.append (Scan.nextline ()). append (Stringutils.newline);        } System.out.println (Builder.tostring ()); } Catch(Exception e) {e.printstacktrace (); }    }
Using Proxyselector

Do not explain more, directly on the code:

 Public Static voidHttpproxy ()throwsIOException {proxyselector.setdefault (NewProxyselector () {@Override PublicList<proxy>Select (Uri uri) {List<Proxy> list =NewArraylist<proxy>(); List.add (NewProxy (Proxy.Type.HTTP,Newinetsocketaddress ("10.10.8.84", 8080))); returnlist; } @Override Public voidconnectfailed (Uri Uri, socketaddress sa, IOException IoE) {System.out.println ("Connection Agent failed!" ");        }        }); //addresses that need to be accessedString urlstr = "http://www.baidu.com"; //Create a connectionURL url =NewURL (URLSTR); URLConnection Conn=url.openconnection (); //Output Access Results        Try{Scanner Scan=NewScanner (Conn.getinputstream ()); StringBuilder Builder=NewStringBuilder ();  while(Scan.hasnextline ()) {Builder.append (Scan.nextline ()). append (Stringutils.newline);        } System.out.println (Builder.tostring ()); } Catch(Exception e) {e.printstacktrace (); }    }

The code above does not explicitly specify a proxy server, but when I provide an invalid proxy IP, the console outputs the word "Connection Broker failed". The description program uses the agent I have provided.

Proxyselector is an abstract class that provides two methods Select, connectfailed needs to be implemented by the user:

    • Select: Returns the list of proxy servers (the first agent will be used by default, according to the test);
    • Connectfailed: The processing method when the connection agent fails.

Java provides an implementation class Defaultproxyselector for Proxyselector and registers it as the default proxy implementation class, which is generally not required to be implemented explicitly, and can be called by Proxyselector.getdefault () when needed. Simply say defaultproxyselector to the realization of Proxyselector:

    • Select: The use of a proxy server is selected based on the system properties. The system properties of the proxy server are as follows three http.proxyhost,http.proxyport,http.nonproxyhosts (see example of how to use it);
    • Connectfailed: The connection agent fails and tries to use a direct connection.

Here is an example (lazy to write, directly on the Internet to find a):

 Packagecom.zhyea.olproxy.test;Importjava.io.IOException;Importjava.net.MalformedURLException;ImportJava.net.URL;Importjava.net.URLConnection;Importjava.util.Properties;ImportJava.util.Scanner; Public classProxyselectortest {//test the network default configuration of the local JVM     Public voidSetlocalproxy () {Properties prop=system.getproperties (); //set HTTP access to the address of the proxy server to useProp.setproperty ("Http.proxyhost", "10.10.8.84"); //to set the port for HTTP access to the proxy server to useProp.setproperty ("Http.proxyport", "8080"); //set HTTP access to hosts that do not need to be accessed through a proxy server.//you can use the * wildcard character, multiple addresses are separated by a |Prop.setproperty ("Http.nonproxyhosts", "localhost|10.20.*"); //set the proxy server address and port used by secure HTTP access//It does not have the Https.nonproxyhosts property, which is accessed according to the rules set in Http.nonproxyhostsProp.setproperty ("Https.proxyhost", "192.168.0.96"); Prop.setproperty ("Https.proxyport", "443"); //sets the host, port, and host for the proxy server to which FTP is accessedProp.setproperty ("Ftp.proxyhost", "10.10.0.96"); Prop.setproperty ("Ftp.proxyport", "2121"); Prop.setproperty ("Ftp.nonproxyhosts", "localhost|10.10.*"); //set the address and port of the SOCKS proxy serverProp.setproperty ("socks. ProxyHost "," 10.10.0.96 "); Prop.setproperty ("Socks. ProxyPort "," 1080 "); }    //Clear proxy Settings     Public voidRemovelocalproxy () {Properties prop=system.getproperties (); //clearing Proxy server settings for HTTP accessProp.remove ("Http.proxyhost"); Prop.remove ("Http.proxyport"); Prop.remove ("Http.nonproxyhosts"); //clearing proxy server settings for HTTPS accessProp.remove ("Https.proxyhost"); Prop.remove ("Https.proxyport"); //clear proxy settings for FTP accessProp.remove ("Ftp.proxyhost"); Prop.remove ("Ftp.proxyport"); Prop.remove ("Ftp.nonproxyhosts"); //clear Proxy server settings for socksProp.remove ("Socksproxyhost"); Prop.remove ("Socksproxyport"); }    //Testing HTTP Access     Public voidShowhttpproxy ()throwsmalformedurlexception, ioexception {URL URL=NewURL ("http://www.baidu.com"); //Open the connection directly, but the system calls the HTTP proxy server just setURLConnection conn = Url.openconnection ();//①Scanner scan =NewScanner (Conn.getinputstream ()); //read the contents of the remote host         while(Scan.hasnextline ()) {System.out.println (Scan.nextline ()); }    }     Public Static voidMain (string[] args)throwsIOException {proxyselectortest test=Newproxyselectortest ();        Test.setlocalproxy ();        Test.showhttpproxy ();    Test.removelocalproxy (); }}

It's all written.

That's it.

Java sockets-Using a proxy server

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.