public void download(String urlString, String filename) throws Exception{
// 构造URL
URL url = new URL(urlString);
// 打开连接
URLConnection con = url.openConnection();
// 输入流
InputStream is = con.getInputStream();
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流
OutputStream os = new FileOutputStream(filename);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
}
异常:
java.io.IOException: Server returned HTTP response code: 400 for URL
URLConnection con = url.openConnection();
// 输入流
con.connect(); //加上这个吧
http://blog.csdn.net/itbiyu/article/details/6981982
将含中文的字符串转义后再去请求
url=url.replace(fileName,URLEncoder.encode(fileName,"UTF-8"));
对于下载图片会出现乱码等问题我给出了解决方案,加上con.connection().写出的时候用ByteArrayOutputStream()方法
String urlString = "http://pic6.huitu.com/res/20130116/84481_20130116142820494200_1.jpg";
try {
URL url = new URL(urlString);
URLConnection con = url.openConnection();
con.connect();
InputStream is = con.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes = new byte[100];
int len=0;
while((len=is.read(bytes))!=-1){
baos.write(bytes, 0, len);
}
FileOutputStream fos = new FileOutputStream(new File("a.jpg"));
fos.write(baos.toByteArray());
fos.close();
is.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}