import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;public class HtmlSourceView {
public static void main(String[] args) {
InputStream in = null;
OutputStream out = null;
try {
URL url = new URL("http://www.csdn.net");
in = url.openStream();
if (args.length == 2) {
out = new FileOutputStream(args[1]);
} else
out = System.out;
byte[] buffer = new byte[4096];
int bytes_read;
while ((bytes_read = in.read(buffer)) != -1) {
out.write(buffer, 0, bytes_read);
}
} catch (Exception e) {
System.err.println(e);
} finally {
try {
in.close();
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
}我是在公司用代理服务器访问网络的,请问为什么我可以用IE访问csdn,但是上面的代码就无法访问?
报错:
java.net.ConnectException: Connection timed out: connect
java.lang.NullPointerException

解决方案 »

  1.   

    需要设置代理,5.0中可以使用Proxy类,例如
    Proxy proxy=new Proxy(Proxy.Type.HTTP,new InetSocketAddress(host,port));
    URL url=new URL(url);
    URLConnection connection=url.openConnection(proxy);
    connection.connect();
    InputStream in=connection.getInputStream();
    5.0之前需要设置系统代理属性
    System.setProperty("proxySet","true");
    System.setProperty("proxyHost",host);
    System.setProperty("proxyPort",port);