package com.path.test; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.net.URL; import java.net.URLConnection; public class TURLConnection { public static void main(String args[]) throws Exception { //设置代理上外网 System.getProperties().put("proxySet", "true"); System.getProperties().put("proxyHost", "172.31.170.14"); System.getProperties().put("proxyPort", "8080"); /* 如果需要验证用户 //Authenticator.setDefault(new MyAuthenticator()); */ URL url=new URL("http://www.csdn.net"); URLConnection urlCon=url.openConnection(); /* * 方法1,一次过读取所有信息 */ BufferedInputStream bis=new BufferedInputStream(urlCon.getInputStream()); BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("C:aa.htm")); byte b[]=new byte[bis.available()]; bis.read(b); bos.write(b); bos.flush(); bis.close(); bos.close(); /* * 方法2,一个个字节地读取 */ // InputStream is=urlCon.getInputStream(); // FileOutputStream fos=new FileOutputStream("C:bb.htm"); // int tmp=0; // while((tmp=is.read())!=-1) // { // fos.write(tmp); // } // fos.flush(); // fos.close(); // is.close(); } }
import java.net.Authenticator; import java.net.PasswordAuthentication; public class MyAuthenticator extends Authenticator { private String name ; private String password; public MyAuthenticator() { super(); // TODO Auto-generated constructor stub } public MyAuthenticator(String name, String password) { super(); // TODO Auto-generated constructor stub this.name = name; this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(this.getName(),this.getPassword().toCharArray()); } }