public class TestImgJsoup {
/**
* @param urlPath
* 图片路径
* @throws Exception
*/
public void getImages(String urlPath, String filePath, String fileName) {
try {
URL url = new URL(urlPath);// :获取的路径
// :http协议连接对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(6 * 10000);
if (conn.getResponseCode() == 200) {
InputStream inputStream = conn.getInputStream();
byte[] data = readStream(inputStream);
if (data.length > (1024 * 10)) {
FileOutputStream outputStream = new FileOutputStream(
filePath + fileName);
outputStream.write(data);
outputStream.close();
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("下载图片出错" + e.getMessage() + " "
+ e.getCause());
}
}
/**
* 读取url中数据,并以字节的形式返回
*
* @param inputStream
* @return
* @throws Exception
*/
public byte[] readStream(InputStream inputStream) throws Exception {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int len = -1;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
outputStream.close();
inputStream.close();
return outputStream.toByteArray();
}
public static void main(String[] args) {
String urlPath="http://www.javaweb.top/images/360_2.jpg";
TestImgJsoup testImgJsoup= new TestImgJsoup();
testImgJsoup.getImages(urlPath, "C:\\", "2345.jpg");
//保存图片
}
}