Development techniques-java through Httpproxy

Source: Internet
Author: User
Tags base64

Requirements DescriptionIn Normal project development requirements, the scenario for connecting a remote server is typically two:1 home implementation of the HTTP server, API interface has been agreed, 2 development platform services, usually such as Sina, Baidu Cloud and other platforms provided by the RESTful interface, the above two scenarios through native URLConnection or Apache provided by the HttpClient Toolkit are     It is convenient to implement the call.    However, the third scenario is the need to connect to foreign open services such as Google, Twitter, Tumblr and other open API interfaces.    Under the great care of GFW, we were told not to talk to strangers ... OK, let's start with a proxy-based traversal!     Ready to work 1 HTTP proxy Server It is recommended to spend some money to buy a stable VPN, with the kind of HTTP proxy. 2 Extranet access test can be tested with chrome Switchyomega plug-in, not directly set up IE System Agent ready to complete, you can begin to develop the design analysis Agent connection implementation of the key steps: First, set the proxy server address port Way One:Java supports setting HTTP proxies and ports in a system.setproperty manner, as follows:
    System.setproperty ("Http.proxyset", "true"); System.setproperty ("Http.proxyhost", proxyhost); System.setproperty ("Http.proxyport", "" "+ ProxyPort); For HTTPS also open proxy system.setproperty ("Https.proxyhost", proxyhost); System.setproperty ("Https.proxyport", "" "+ ProxyPort);

  

       Detailed settings for Java properties can be found in: http://docs.oracle.com/javase/6/docs/technotes/guides/net/properties.html Way Two:Using the proxy object, you can inject it into the urlconnection when the connection is established:
Initialize proxy object Proxy proxy = new Proxy (Proxy.Type.HTTP, new Inetsocketaddress (ProxyHost, ProxyPort)); Create connection URL u = new url (URL); URLConnection conn = u.openconnection (proxy);

  

A comparison of two waysThe first way is more recommended, when you adopt the URLConnection-based package implementation of the class library, the use of setproperty in the way you do not need to move the inside of the code, green light. Second, the realization of user password check Way One:Officer information is written to the HTTP header, and the user name password is Base64 encoded after the Proxy-authorization header is set:
String Headerkey = "Proxy-authorization"; String encoded = new String (Base64.encodebase64 ((new string (Proxyuser + ":" + Proxypass). GetBytes ())); String headervalue = "Basic" + encoded;conn.setrequestproperty (Headerkey, Headervalue);
A lot of information will be recommended in this way, but after testing,This mode does not work correctly in the HTTPS demand scenario! Way Two:Implement the authenticator interface and inject it as a global validator:
public static class Myauthenticator extends Authenticator {    String userName;    String password; Public Myauthenticator (String userName, string password) {    this.username = userName;    This.password = password;} /*** automatically triggered when a password check is required */@Overrideprotected passwordauthentication getpasswordauthentication () {    return new Passwordauthentication (UserName, Password.tochararray ());}}
 To inject a validation instance before performing a connection:
Myauthenticator auth = new Myauthenticator (Proxyuser, Proxypass); Authenticator.setdefault (auth);

  

Instance CodeEntry Class
/** * Network Agent Test * * <pre> * Set proxy host and port: System variable (HTTPS requires synchronization settings) * Set Proxy authentication method: Global Proxy Object * * * HTTPS link Error: * Unable to tunnel throug H Proxy. Proxy returns "http/1.0 407 proxy Authentication Required" * Resolve with Global agent validation * * </pre> * * @author Tzz * @createDate 2    015 Year July 23 * */public class Proxytest {private static String ProxyHost = "xxx.xxxxx.com";    private static int proxyport = 8080;    private static String Proxyuser = "user";    private static String Proxypass = "Pass";        public static void Main (string[] args) {String url = "https://www.google.com/";        String content = doproxy (URL);    System.out.println ("Result: ===================\n" + content);        /** * The proxy is implemented through system variables * * @param URL * @return */public static string Doproxy (string url) {        Set the system variable System.setproperty ("Http.proxyset", "true");        System.setproperty ("Http.proxyhost", proxyhost);        System.setproperty ("Http.proxyport", "" "+ ProxyPort); For HTTPS also open agent System.setproperty ("Https.proxyhost", proxyhost);        System.setproperty ("Https.proxyport", "" "+ ProxyPort);        Set the default validator Setdefaultauthentication ();            Start request try {URL u = new url (URL);            URLConnection conn = U.openconnection ();            Httpsurlconnection Httpscon = (httpsurlconnection) conn;            Httpscon.setfollowredirects (TRUE);            String encoding = conn.getcontentencoding ();            if (stringutils.isempty (encoding)) {encoding = "UTF-8";            } InputStream is = Conn.getinputstream ();            String content = ioutils.tostring (is, encoding);        return content;            } catch (Exception e) {e.printstacktrace ();        return E.getmessage (); }}/** * Set global Validator Object */public static void Setdefaultauthentication () {Basicauthenticator auth = n        EW Basicauthenticator (Proxyuser, Proxypass); Authenticator.setdefault (AUth); }}
Checker
    /**     * Implement sun.net Proxy Verification     *      * @author tzz     * @createDate July 23, 2015 *    */public static class Basicauthenticator extends Authenticator {        String userName;        String password;        Public Basicauthenticator (String userName, string password) {            this.username = userName;            This.password = password;        }        /**         * Called when password authorization is needed. Subclasses should override the default implementation, which returns NULL.         *          * @return The passwordauthentication collected from the user, or null if none is provided.         */        @Override        protected passwordauthentication getpasswordauthentication () {            //system.out.println (" DEBUG = = = Use global authentication of password ");            return new Passwordauthentication (UserName, Password.tochararray ());        }    }
FAQ Connection exceptionunable to tunnel through proxy. Proxy returns "http/1.0 407 proxy authentication Required"Usually the proxy server fails to read the authentication information, check to see if the destination URL is an HTTPS connection and that the global authenticator class is set correctly.

Development techniques-java through Httpproxy

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.