As the company on the Internet to implement agency mechanism,
And recently, I've been studying OPENAPI on the web.
There is no way to use the agent, I previously an article introduced the HttpClient proxy usage,
This article describes how to use the proxy for basic java.
The most commonly used global configuration agent.
Java code
- Properties prop = System.getproperties ();
- //HTTP proxy IP Settings
- Prop.setproperty ("Http.proxyhost", "10.28.0.254");
- //HTTP proxy port settings
- Prop.setproperty ("Http.proxyport", "80");
- //You can also set the address that does not need to use the proxy
- Prop.setproperty ("http.nonproxyhosts", "localhost|10.28.0.*");
- //Set the proxy server address and port for HTTPS secure access
- Prop.setproperty ("Https.proxyhost", "10.28.0.254");
- Prop.setproperty ("Https.proxyport", "443");
- The filter address property for secure access is also http.nonproxyhosts and not https.nonproxyhosts
- //ftp proxy settings into the next
- Prop.setproperty ("Ftp.proxyhost", "192.168.0.254");
- Prop.setproperty ("Ftp.proxyport", "2121");
- Prop.setproperty ("ftp.nonproxyhosts", "localhost|192.168.0.*");
- proxy settings for//socks
- Prop.setproperty ("Socksproxyhost", "192.168.0.254");
- Prop.setproperty ("Socksproxyport", "8000");
Sometimes proxies need to be authenticated at this point we need to define a class that inherits the class authenticator.
Java code
- Public class Myauthenticator extends Authenticator {
- private String username = "";
- private String Password = "";
- Public Myauthenticator (string Username, string password) {
- this.username = Username;
- This.password = password;
- }
- protected Passwordauthentication getpasswordauthentication () {
- Returnnew passwordauthentication (username, Password.tochararray ());
- }
- }
- Set the user name and password to log on to the proxy server
- Authenticator.setdefault (new Myauthenticator ("UserName", "Password"));
Of course, this method can meet most of the requirements but there are some limitations,
Is that all connections are configured by proxy with a unified attribute and cannot be configured for a specific connection.
JDK5 and later releases introduce a new proxy configuration that can be configured for a specific connection
Java code
- URL url = new URL ("http://www.shanhe114.com");
- //Create Proxy Server
- Inetsocketaddress addr = new Inetsocketaddress ("10.28.0.4",
- 8080);
- //proxy proxy = new Proxy (Proxy.Type.SOCKS, addr);//socks Agent
- Proxy proxy = new Proxy (Proxy.Type.HTTP, addr); //http Agent
- //Other ways to see Proxy.type properties
- URLConnection conn = url.openconnection (proxy);
- InputStream in = Conn.getinputstream ();
- //inputstream in = Url.openstream ();
- String content = ioutils.tostring (in);
- SYSTEM.OUT.PRINTLN (content);
Common proxy settings for Java