對於在局域網內發布的java應用程序,由於其沒有直接連接在internet上,所以不能直接用java.net.URL訪問網上資源。在這種情況下,需要為java.net.URL指定代理服務器,指定方法如下所示:
import java.util.Properties;
import java.net.*;
import java.io.*;
public class TestHttpProxy {
public static void main(String[] args) {
String sUrl = "http://java.sun.com/index.html";
Properties prop = System.getProperties();
prop.put("http.proxyHost","192.168.1.111");
prop.put("http.proxyPort","80");
try{
URL su = new URL(sUrl);
System.out.println("url : " + su);
URLConnection uc = su.openConnection();
System.out.println("uc : " + uc);
InputStream is = su.openStream();
System.out.println("ic : " + is.read());
is.close();
System.out.println("ok");
} catch(Exception e) {
e.printStackTrace();
}
}
}