Description of requirementsIn the Normal project development requirements. The scenario for connecting to a remote server typically has two:1 Your own HTTPSERVER,API interface has been agreed. 2 Development platform Services. Usually such as Sina, Baidu Cloud and other platforms provide a restful interface. The two scenarios above can be easily implemented by native URLConnection or the HttpClient Toolkit provided by Apache.
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 ... Well, let's start with a proxy-based traversal!
Ready to work 1 HTTP proxy Server recommends spending a bit of money to buy a stable VPN, the kind with an HTTP proxy. 2 Internet access testing can be tested with the Chrome Switchyomega plugin. Not directly set up IE System Agent ready to complete. Be able to start developing the key steps of the design Analysis Agent Connection implementation: First, set the proxy server address port mode one:Java supports setting HTTP proxies and ports in System.setproperty, such as the following:
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);
For specific settings for Java properties, refer to: http://docs.oracle.com/javase/6/docs/technotes/guides/net/properties.html
Way Two:Using the proxy object, you can inject it into urlconnection when you make a connection:
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);
comparison of the two methodsThe first way is more recommended, when you adopt a class library based on the URLConnection package implementation, 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 calibration method One: Officer information written to the HTTP header, the Usernamepassword base64 encoding after the set Proxy-authorization header:
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 recommend this way. But after testing,This mode does not work correctly in the HTTPS demand scenario!
mode two: implement authenticator interface. and injected 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;} /*** when you need to use a password check yourself trigger */@Overrideprotected passwordauthentication getpasswordauthentication () { return new Passwordauthentication (UserName, Password.tochararray ());}}
To inject a validation instance before running the connection:
Myauthenticator auth = new Myauthenticator (Proxyuser, Proxypass); Authenticator.setdefault (auth);
Instance Code ingress 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 thro Ugh 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 Basica Uthenticator 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"Typically, agent server fails to read the validation information, check that the destination URL is an HTTPS connection, and that the global authenticator class is set correctly.
Development techniques-java through Httpproxy