Proxy principles in Java and examples of proxy usage _java

Source: Internet
Author: User
Tags static class

Today, when you test the socket programming, you cannot connect to the extranet. The company is using an HTTP proxy. Internet search did not read too well, so spend a lot of time to learn. Look at the relationship between HTTP and TCP protocol is good, only understand. Now can use the HTTP proxy through the socket, the result is very simple, the process is very difficult.

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

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

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

IP: Is the network layer protocol.

A TCP connection will be three handshake (like a transfer account, unknown), HTTP is just an application protocol, that is, the equivalent of a custom protocol, that is, it does not interfere with the underlying transmission mode, but the data content format is defined. 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 a language that both sides can understand <TCP/IP>). Similarly, FTP, Telnet is an application layer protocol, for example, for FTP, others say "SB", you Answer "hey", but the format content is different.

2. After recognizing the above, we say that the HTTP proxy, from the above can be understood, HTTP proxy server is such a machine: you send all HTTP requests (whether to request Baidu or Google) are sent to this HTTP proxy server, The HTTP proxy server then requests the final address you want to access and passes the response back to you. It is also important to note that it proxies the HTTP protocol, and HTTP is based on TCP, which means that the server proxy is a TCP connection that specifies the HTTP content format. It's no fun talking about it, look at the following code:

Copy Code code as follows:

The following address is the address of the proxy server
Socket socket = new Socket ("10.1.2.188", 80);
Write and content is to follow the HTTP request protocol format content, request Baidu
Socket.getoutputstream (). Write (New String ("Get http://www.baidu.com/http/1.1\r\n\r\n"). GetBytes ());
Byte[] bs = new byte[1024];
InputStream is = Socket.getinputstream ();
int i;
while ((i = Is.read (BS)) > 0) {
System.out.println (New String (BS, 0, I));
}
Is.close ();

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

Copy Code code as follows:

Set up agents
System.setproperty ("Http.proxyset", "true");
System.setproperty ("Http.proxyhost", "10.1.2.188");
System.setproperty ("Http.proxyport", "80");

Direct Access Destination Address
URL url = new URL ("http://www.baidu.com");
URLConnection con = url.openconnection ();
InputStreamReader ISR = new InputStreamReader (Con.getinputstream ());
Char[] cs = new char[1024];
int i = 0;
while ((i = Isr.read (cs)) > 0) {
System.out.println (New String (CS, 0, i));
}
Isr.close ();

Finally, summarize:

In an environment where HTTP proxies are used,

If you are using socket (TCP) to connect to the extranet, connect directly to the proxy server, and then specify the extranet URL to forward to in the HTTP request sent.

If you are using a 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, look at the following code, use the NIO socket through the HTTP proxy access to the extranet example:

Copy Code code as follows:

Socketchannel sc = socketchannel.open (new inetsocketaddress ("10.1.2.188", 80));

Sc.write (Charset.forname ("UTF8"). Encode ("Get http://www.baidu.com/http/1.1\r\n\r\n");

Bytebuffer buffer = bytebuffer.allocate (1024);

while (sc.read (buffer)!=-1) {
Buffer.flip ();
System.out.println (Charset.forname ("UTF8"). decode (buffer);
Buffer.clear ();
}
Sc.close ();

Example of adding agents to Java socket programming

Sometimes our network can not directly connect to the extranet, you need to use HTTP or HTTPS or the socket agent to connect to the extranet, here is the Java use Agent to connect to the extranet some of the methods: Method one use System properties to complete proxy settings, this method is relatively simple, However, you cannot set the proxy on a separate connection:

Copy Code code as follows:

public static void Main (string[] args) {
Properties prop = System.getproperties ();
Set the address of the proxy server to use for HTTP access
Prop.setproperty ("Http.proxyhost", "192.168.0.254");
Set HTTP access to the port of the proxy server to use
Prop.setproperty ("Http.proxyport", "8080");
To set up a host that does not need to be accessed through a proxy server, you can use the * wildcard character and multiple addresses to separate
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, which is accessed by the rules set in http.nonproxyhosts
Prop.setproperty ("Https.proxyhost", "192.168.0.254");
Prop.setproperty ("Https.proxyport", "443");
Hosts and ports using the FTP proxy server and hosts that do not need to use the FTP proxy server
Prop.setproperty ("Ftp.proxyhost", "192.168.0.254");
Prop.setproperty ("Ftp.proxyport", "2121");
Prop.setproperty ("Ftp.nonproxyhosts", "localhost|192.168.0.*");
Address and port of the SOCKS proxy server
Prop.setproperty ("Socksproxyhost", "192.168.0.254");
Prop.setproperty ("Socksproxyport", "8000");
Set user name and password to log on to proxy server
Authenticator.setdefault (New Myauthenticator ("UserName", "Password"));
}
Static class Myauthenticator extends Authenticator {
Private String user = "";
Private String Password = "";
Public Myauthenticator (string user, string password) {
This.user = user;
This.password = password;
}
Protected Passwordauthentication getpasswordauthentication () {
Returnnew passwordauthentication (User, Password.tochararray ());
}
}

Method two uses proxy to implement a proxy for each connection, which can only be used in versions above JDK 1.5 (including jdk1.5), with the advantage that it is possible to set the proxy for each connection individually, with the disadvantage of setting up a more cumbersome:
Copy Code code as follows:

public static void Main (string[] args) {
try {
URL url = new URL ("http://www.baidu.com");
Creating a proxy Server
Inetsocketaddress addr = new Inetsocketaddress ("192.168.0.254",
8080);
Proxy proxy = new Proxy (Proxy.Type.SOCKS, addr); Socket Agent
Proxy proxy = new Proxy (Proxy.Type.HTTP, addr); HTTP Proxy
If we know the name of the proxy server, we can use it directly.
End
URLConnection conn = url.openconnection (proxy);
InputStream in = Conn.getinputstream ();
InputStream in = Url.openstream ();
String s = ioutils.tostring (in);
System.out.println (s);
catch (Exception e) {
E.printstacktrace ();
}
}

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.