对于在局域网内发布的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();
}
}
}