Using proxies in Java HTTP connections (httpurlconnection) and their validation (authentication)

Source: Internet
Author: User
Tags base64

Using the Java HttpURLConnection class allows you to implement HttpClient functionality without having to rely on any other class library. All at times people use it directly to accomplish some simple (or complex) functions. But you live behind the great {print G.F.W}, and if the site you need to access is a wall, the HttpURLConnection class will have a connection timeout error. This is the time to set up a proxy for him.

There are two ways to set up an agent (proxy):

1. By setting the System Properties (System.setpropery (string key, String value)

First you can see the properties supported by Java here. We can use these two properties in the Http.proxyhost,http.proxyport. As the name implies, the proxy server address and proxy port are set separately.

//在你发起Http请求之前设置一下属性   //通知Java您要通过代理进行连接         System.getProperties().put("proxySet", "true");        //指定代理所在的服务器         System.getProperties().put("proxyHost", "127.0.0.1");        //指定代理监听的端口         System.getProperties().put("proxyPort", "8580");

Or

System.setProperty("http.proxyHost", "www.proxy.com");  System.setProperty("http.proxyPort", "8080");

  

Replace the above www.proxy.com for your proxy server address or IP address, and the corresponding port for the real port, HTTP connection and can work. It is important to note that if you set these properties, all HTTP requests will be made through the proxy server. These properties are JVM-level and are set to be valid for all similar requests at a later time. For example, the above is about HTTP, and about FTP and so on.

If your proxy server does not need to be verified, it will be over. However, it is generally necessary to verify. But if you look at the list of properties supported by Java above, you will find that there is no expected

    1. Http.proxyusername=username
    2. Http.proxypassword=password

These two properties. In this case, the Java.net.Authenticator class is required to complete the general HTTP validation. But the Java.net.Authenticator class is an abstract class, and we want to use the class that we need to instantiate all of a sudden. Personally, it's inconvenient here. As follows:

  1. Publicclass Basicauthenticator extends Authenticator {
  2. String UserName;
  3. String password;
  4. Public basicauthenticator (string userName, string password) {
  5. this.username = userName;
  6. this.password = password;
  7. }
  8.  /**
  9. * Called when password authorization is needed. Subclasses should
  10. * Override the default implementation, which returns NULL.
  11. *
  12. * @return The passwordauthentication collected from the
  13. * User, or null if none is provided.
  14. */
  15. @Override
  16. protected passwordauthentication getpasswordauthentication () {
  17. returnnew passwordauthentication (UserName, Password.tochararray ());
  18. }
  19. }

We need to overwrite the Getpasswordauthentication () method of the Java.net.Authenticator class and return a passwordauthentication instance. To make him work, you also need to set

    1. Authenticator.setdefault (new basicauthenticator (userName, password));

This provides authentication based on HTTP basic and then allows for a smooth use of the agents that need to be validated.

2, through the Java.net.Proxy class.

This approach is to instantiate a proxy class that provides proxies for information, such as ports and addresses.

    1. Proxy proxy = new Proxy (Proxy.Type.HTTP, new inetsocketaddress (host, Port));
    2. URLConnection conn = url.openconnection (proxy);

A proxy is used by passing a proxy parameter when an HTTP connection is opened. If you need to verify the information, we can add an HTTP header parameter to implement.

    1. Format: "proxy-authorization" = "Basic base64.encode (User:password)"
    2. String Headerkey = "proxy-authorization";
    3. String headervalue = "Basic" + base64.encode (user+":" +password);
    4. Conn.setrequestproperty (Headerkey, Headervalue);
    5. //..........

Base64.encode (User:password) refers to the use of BASE64 encoded values as part of the value after the user name and password are concatenated with a colon.

In this way, only specific HTTP connections are affected, but the code needs to be modified. Whether the authenticator can be used in this way is not yet verified.

Using proxies in Java HTTP connections (httpurlconnection) and their validation (authentication)

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.