In practice, due to office network restrictions, you must specify a proxy when connecting to the Internet,
However, when accessing servers with some virtual host domain names, there is no corresponding DNS resolution record. Therefore, it is very troublesome to manually configure the hosts file for ing.
According to the java.net. url API, we sorted out how to set the proxy server and customize the Host header to bypass DNS resolution:
The Code is as follows:
[Code]
Public static void main (string [] ARGs) throws ioexception {
/**
* The following method is set globally and is not recommended. System. setproperty ("proxyset", "true ");
* System. setproperty ("proxyhost", "proxy.lizongbo.com ");
* System. setproperty ("proxyport", "8080 ");
*/
String urlstr = "http://about.me/lizongbo ";
Urlstr = "http://about.me/lizongbo ";
Httpurlconnection httpconn = NULL;
Stringbuilder sb = new stringbuilder ();
URL url = new URL (urlstr );
String hostname = URL. gethost ();
// Customize the IP address in the URL according to the configuration
If (hostname. tolowercase (). endswith (". mqq. Im ")){
Url = new URL (urlstr. Replace (hostname, "127.0.0.1 "));
}
System. Out. println (URL );
Proxy proxy = new proxy (proxy. type. HTTP, new inetsocketaddress (
"Proxy.lizongbo.com", 8080 ));
// Only use HTTP proxy for the current connection
Httpconn = (httpurlconnection) URL. openconnection (proxy );
Httpconn. setrequestmethod ("get ");
// Manually set the Host header to support virtual hosts. In this way, you can avoid the trouble of manually configuring/etc/hosts to bypass DNS resolution, especially when the program runs on different servers, It is very practical.
Httpconn. setrequestproperty ("host", hostname );
Httpconn. setconnecttimeout (5000 );
Httpconn. Connect ();
Inputstream is = httpconn. getinputstream ();
Bufferedreader BR = new bufferedreader (New inputstreamreader (is,
"UTF-8 "));
String line = NULL;
While (line = Br. Readline ())! = NULL ){
SB. append (Line). append ('\ n ');
}
// Close the connection
Httpconn. Disconnect ();
System. Out. println (SB );
}
[/Code]
Reprinted from: http://618119.com/archives/2010/12/23/202.html