Full code
Package com.proj.net;//Import encoded JAR file import It.sauronsoftware.base64.base64;import Java.io.bufferedinputstream;import Java.io.bufferedreader;import Java.io.inputstreamreader;import Java.net.httpurlconnection;import java.net.URL;/** * Very many companies will restrict the network, through the proxy server and password ability to connect the extranet.<br> * This way has a lot of advantages:<br> * 1, security. Proxy server like a layer of filtering layer;<br> * 2, cost-saving, only need to allocate a very small number of IP addresses can;<br> * 3, the staff can be personalized online configuration, to avoid someone to download a large amount of data caused by network congestion. <br> * * This article introduces how to cross LAN in the program through a small case.
<br> * For people who engage in web development. But for those who do Java EE application development, they can participate. <br> * * @author Wang Yiyang * * 2014-10-30 * */public class Test {public static void main (string[] args) {try {//Two way set proxy server//Set Agent 1//proxy proxy = new Proxy (proxy.type.http,new inetsocketaddress ("", 80));//Set Agent 2system.getproperties (). SetProperty ("Http.proxyhost", "" "); System.getproperties (). SetProperty ("Http.proxyport", "" "); String urlstring = "http://blog.csdn.net/"; URL url = new URL (urlstring);//The first set method//httpurlconnection URLConnection = (httpurlconnection) url.openconnection ( proxy); HttpURLConnection URLConnection = (httpurlconnection) url.openconnection (); Urlconnection.setrequestmethod ("GET"); Urlconnection.setconnecttimeout (1000);//Set User Agenturlconnection.setrequestproperty ("User-agent", "Mozilla/4.0 ( Compatible MSIE 5.0; Windows NT; Digext);//set access to username and Passwordurlconnection.setrequestproperty ("Proxy-authorization", "Basic" + Base64.encode ("Username:password")); Urlconnection.connect (); System.out.print (UrlconnecTion.getresponsecode ()); Bufferedinputstream bis = new Bufferedinputstream (Urlconnection.getinputstream ()); InputStreamReader ISR = new InputStreamReader (bis, "UTF-8"); BufferedReader BufferedReader = new BufferedReader (ISR); String str = ""; StringBuffer buffer = new StringBuffer (""), while ((str = bufferedreader.readline ())!=null) {buffer.append (str+ "\ r \ n");} SYSTEM.OUT.PRINTLN (buffer);} catch (Exception e) {e.printstacktrace ();}}}
Back to code:200,ok!
Exception server returned HTTP response code:403 for URL
After Url.openconnection (), add:
Connection.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 5.0; Windows NT; Digext) ");
Java Internet via proxy server