java通过http下载图片_使用http协议将服务器图片下载到本地

本文介绍了如何在Java中使用HTTP协议从服务器下载图片。首先,创建一个Java Web项目,提供图片资源;然后,客户端使用HttpURLConnection通过GET请求获取图片输入流,并将其保存到本地文件系统。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 服务器端新建java web项目

a2ce9239a260820190b22afbf7ef4f72.png

该图片资源路径为   http://localhost:8080/httppost/android.jpg

2 客服端

8c79c0b037775fa5a2a9742d090698ea.png

HttpUtils.java 代码如下:

package com.zwh.http;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

public class HttpUtils {

private static String URL_PATH = "http://localhost:8080/httppost/android.jpg";

public HttpUtils() {

// TODO Auto-generated constructor stub

}

public static void saveToDisk() {

// 获取输入流

InputStream inputStream = getInputStream();

byte[] date = new byte[1024];

int len = 0;

FileOutputStream fileOutputStream = null;

try {

fileOutputStream = new FileOutputStream("F://example.jpg");

while ((len = inputStream.read(date)) != -1) {

fileOutputStream.write(date, 0, len);

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

try {

if (inputStream != null) {

inputStream.close();

}

if (fileOutputStream != null) {

fileOutputStream.close();

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

/**

* @return

*/

public static InputStream getInputStream() {

InputStream inputStream = null;

HttpURLConnection httpURLConnection = null;

try {

URL url = new URL(URL_PATH);

httpURLConnection = (HttpURLConnection) url.openConnection();

// 设置连接网络的超时时间

httpURLConnection.setConnectTimeout(3000);

httpURLConnection.setDoInput(true);

httpURLConnection.setRequestMethod("GET");

int responseCode = httpURLConnection.getResponseCode();

if (responseCode == 200) {

inputStream = httpURLConnection.getInputStream();

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return inputStream;

}

public static void main(String[] args) {

HttpUtils httpUtils = new HttpUtils();

httpUtils.saveToDisk();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值