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;/** * Many companies will restrict the Internet by proxy server and password to connect to the extranet. <br> * There are many benefits in this way:<br> * 1, security, proxy server like a layer of filter layer;<br> * 2, cost-saving, only need to allocate a small number of IP addresses can be;<br> * 3, the staff on the Internet can be personalized configuration, Avoid people downloading large amounts of data and causing network congestion. <br> * * This article is a small case to show how to cross the LAN in the program to access the extranet. <br> * For people who engage in web development, it's trivial, but for developers of Java EE applications, it can be a reference. <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 proxy 2system.getproperties (). SetProperty ("Http.proxyhost", "" "); System.getproperties (). SetProperty ("Http.proxyport", "" "); String urlstring = "http://blog.csdn.net/"; URL url = new URL (urlstring),//corresponds to the first setting//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 the user name and password to access Urlconnection.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
Add after Url.openconnection ():
Connection.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 5.0; Windows NT; Digext) ");
Java Internet via proxy server