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


1 服务器端新建java web项目

使用http协议将服务器图片下载到本地_第1张图片


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

2 客服端

使用http协议将服务器图片下载到本地_第2张图片


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();

	}

}


你可能感兴趣的:(使用http协议将服务器图片下载到本地)