Java proxy usage and agent principle

Source: Internet
Author: User

When you test socket programming today, you cannot connect to the extranet. The company is using an HTTP proxy. Internet search also did not read too much, so spent a lot of time to learn. See the HTTP and TCP protocol relationship is good, only understand. can now use the HTTP proxy through the socket, the result is very simple, the process is very difficult.

1. First briefly talk about HTTP and TCP (the specific content of Google, a lot of information is very full), here to talk about the main points:

HTTP: Is the application layer protocol, which is based on the Transport Layer protocol.

TCP: Is the Transport layer protocol, which is based on the network layer protocol.

IP: Is the network layer protocol.

A TCP connection takes three handshakes (as in the case of a Transfer account), HTTP is just an application protocol, which is the equivalent of a custom protocol that does not interfere with the underlying transmission, but only defines the format of the data content. For example, when someone says "SB" (your name), you answer "yes", just the content format, without changing the way the sound is transmitted (via Sonic Transmission < network hardware media, through the language <TCP/IP> that both can understand). Similarly, FTP, Telnet is also an application layer protocol, for example, for FTP, others say "SB", you Answer "Ah", only the format content is different.

2. After recognizing the above, we say that the HTTP proxy, from the understanding, HTTP proxy server is such a machine: you send all HTTP requests (whether you want to request Baidu or Google) to the HTTP proxy server, The HTTP proxy server then requests the final address you want to access, sending the response back to you. It is also important to note that it proxies the HTTP protocol, and HTTP is TCP-based, which means that the server proxy is a TCP connection that specifies the HTTP content format. Besides, it's not fun anymore, look at the following code:

Java code
  1. The following address is the address of the proxy server
  2. Socket socket = new socket ("10.1.2.188", 80);
  3. Write the content is to follow the HTTP request protocol format content, request Baidu
  4. Socket.getoutputstream (). Write (new String ("GET http://www.baidu.com/http/1.1\r\n\r\n"). GetBytes ());
  5. byte[] bs = new byte[1024];
  6. InputStream is = Socket.getinputstream ();
  7. int i;
  8. while ((i = Is.read (BS)) > 0) {
  9. System.out.println (new String (BS, 0, i));
  10. }
  11. Is.close ();

Of course, in Java, there is proxy agent to use the Internet, at this time using the URL (HTTP) does not involve the socket (TCP), see the following code

Java code
  1. Set up Proxy
  2. System.setproperty ("Http.proxyset", "true");
  3. System.setproperty ("Http.proxyhost", "10.1.2.188");
  4. System.setproperty ("Http.proxyport", "80");
  5. Direct access to Destination address
  6. URL url = new URL ("http://www.baidu.com");
  7. URLConnection con = url.openconnection ();
  8. InputStreamReader ISR = new InputStreamReader (Con.getinputstream ());
  9. Char[] cs = new char[1024];
  10. int i = 0;
  11. while ((i = Isr.read (cs)) > 0) {
  12. System.out.println (new String (CS, 0, i));
  13. }
  14. Isr.close ();

Finally, summarize:

In an environment that uses an HTTP proxy,

If you are using a socket (TCP) to connect to the extranet, connect to the proxy server directly, and then indicate the outgoing URL to be forwarded to in the HTTP request sent.

If you use URL (http) to connect to the extranet, you need to set the HTTP proxy parameters or use proxy.

OK, understand that you can use it later, see the following code, using the NIO socket via HTTP proxy access to the external network example:

Java code
  1. Socketchannel sc = socketchannel.open (new Inetsocketaddress ("10.1.2.188", 80));
  2. Sc.write (Charset.forname ("UTF8"). Encode ("GET http://www.baidu.com/http/1.1\r\n\r\n");
  3. Bytebuffer buffer = bytebuffer.allocate (1024);
  4. while (sc.read (buffer)! =-1) {
  5. Buffer.flip ();
  6. System.out.println (Charset.forname ("UTF8"). Decode (buffer));
  7. Buffer.clear ();
  8. }
  9. Sc.close ();

"The following is from the blog from others": http://hi.baidu.com/splike/blog/item/ed2191d7c94360d1a144dfe3.html

Adding proxies in Java socket programming 2010-06-02 11:12
Sometimes our network can not directly connect to the external network, we need to use HTTP or HTTPS or socket proxy to connect to the external network, here is the Java Use Proxy connection to the external network of some methods,: Method one uses the system properties to complete proxy settings, this method is relatively simple, However, you cannot set the proxy for a separate connection: PublicStaticvoidMain (string[] args) {Properties prop = System.getProperties();        //  set HTTP access to the address of the proxy server to use          prop.setproperty ("Http.proxyhost",  "192.168.0.254");         //  set HTTP access to the port of the proxy server you want to use         prop.setproperty (" Http.proxyport ", " 8080 ");        //  set up a host that does not need to be accessed through a proxy server, you can use * Wildcard characters, multiple addresses with | dividers         prop.setproperty ("http.nonproxyhosts",  "localhost| 192.168.0.* ");        //  set the proxy server address and port used for secure access          //  It does not have the Https.nonproxyhosts property, it is accessed according to the rules set in http.nonproxyhosts           prop.setproperty ("Https.proxyhost",  "192.168.0.254");         prop.setproperty ("Https.proxyport",  "443");         //  primary using the FTP proxy serverservers, ports, and hosts that do not require an FTP proxy server         prop.setproperty ("Ftp.proxyhost",  " 192.168.0.254 ");        prop.setproperty (" Ftp.proxyport ", " 2121 ");         prop.setproperty ("ftp.nonproxyhosts",  "localhost|192.168.0.*");         //SOCKS Proxy server address and port         Prop.setproperty ("Socksproxyhost",  "192.168.0.254");        Prop.setproperty ("Socksproxyport",  "8000");        //  Set the user name and password         Authenticator login to the proxy server.SetDefault(NewMyauthenticator ("UserName", "Password")); }StaticclassMyauthenticatorextendsAuthenticator {PrivateString user = "";PrivateString password = ""; PublicMyauthenticator (string user, string password) { This. user = user; This. Password = password; }protectedPasswordauthentication getpasswordauthentication () {returnNewPasswordauthentication (User, Password.tochararray ()); }} method two use proxy to implement the proxy for each connection, this method can only be used in the version of JDK 1.5 or more (including jdk1.5), the advantage is that each connected agent can be set separately, the disadvantage is that the setup is more troublesome: PublicStaticvoidMain (string[] args) {Try{URL url =NewURL ("http://www.baidu.com"); Create Proxy server Inetsocketaddress addr =NewInetsocketaddress ("192.168.0.254 ",8080); Proxy proxy = new Proxy (Proxy.Type.SOCKS, addr); Socket Agent Proxy proxy =NewProxy (Proxy.type.HTTP, addr); HTTP Proxy//If we know the name of the proxy server, you can use//end URLConnection conn = Url.openconnection (pro            XY);            InputStream in = Conn.getinputstream ();            InputStream in = Url.openstream (); String s = ioutils.toString(in); System. out. println (s); }Catch(Exception e)        {E.printstacktrace (); }    }

Java proxy usage and agent principle

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.