Java使用Http实现网络图片的下载

本文详细介绍了如何使用Java的HttpURLConnection或HttpClient类从网络上下载图片,包括设置URL、建立连接、读取响应及保存文件的步骤,适用于Java开发者进行网络资源下载操作。
package com.io.image.demo;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 通过URL下载网络图片到本地
 */
public class DownLoadImageByHttp 
{
/**
* 把图片资源保存到本地

* @param urlPath 网络图片的地址
* @param localPath 保存到本地的图片路径
* @param fileName 图片的名称
*/
public void downLoadImageToDisk(String urlPath,String localPath, String fileName)
{
FileOutputStream fos = null;
byte[] bytes = null;
File file = null;
try 
{
file = new File(localPath + File.separator + fileName);
bytes = getImageFromNetByUrl(urlPath);
fos = new FileOutputStream(file);
fos.write(bytes);
fos.flush();
fos.close();
}
catch (FileNotFoundException e) 
{
e.printStackTrace();
catch (IOException e) 
{
e.printStackTrace();
}
}

/**
* 通过URL获取网络图片

* @param urlPath 网络图片的地址
* @return
*/
private byte[] getImageFromNetByUrl(String urlPath)
{
HttpURLConnection httpConn = null;
InputStream inStream = null;
byte[] bytes = null;
try 
{
URL url = new URL(urlPath);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("GET");
httpConn.setConnectTimeout(5*1000);
httpConn.setDoInput(true);
httpConn.connect();

if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) 
{
inStream = httpConn.getInputStream();
bytes = readInputStream(inStream);
}

return bytes;
catch (MalformedURLException e) 
{
e.printStackTrace();
catch (IOException e) 
{
e.printStackTrace();
}

return null;
}

/**
* 从输入流读取数据,写到输出流中

* @param inStream 图片的输入流数据
* @return
*/
private byte[] readInputStream(InputStream inStream) 
{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];  
          int len = 0;  
          try 
        {
while((len=inStream.read(bytes)) != -1 )
{  
   outStream.write(bytes, 0, len);  
}
inStream.close();
          catch (IOException e) 
{
e.printStackTrace();

}  

return outStream.toByteArray();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值