package com.ljq.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.junit.Test;

/**
* 从互联网获取图片且保存到指定目录里
*
*
@author jiqinlin
*
*/
public class InternetTest {

@SuppressWarnings(
"static-access")
@Test
public void getImg() throws Exception {
String urlPath
= "http://i0.itc.cn/20101116/62d_67fd2b2a_207d_4de2_a4f9_fb93cc8da492_0.jpg";
URL url
= new URL(urlPath);
HttpURLConnection conn
= (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(
6*1000); // 注意要设置超时,设置时间不要超过10秒,避免被android系统回收
if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream inSream
= conn.getInputStream();
//把图片保存到项目的根目录
new InternetTest().readAsFile(inSream, new File("sohu.jpg"));
}

public static void readAsFile(InputStream inSream, File file) throws Exception{
FileOutputStream outStream
= new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = -1;
while( (len = inSream.read(buffer)) != -1 ){
outStream.write(buffer,
0, len);
}
outStream.close();
inSream.close();
}

}

相关文章:

  • 2022-12-23
  • 2021-12-02
  • 2022-12-23
  • 2021-07-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-13
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-23
  • 2022-12-23
相关资源
相似解决方案