Java --- 使用HttpURLConnection连接网络

package com.chalmers.httputils;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 * @author Chalmers
 * @version 创建时间:2016年2月7日 下午6:13:11
 */
public class HttpUtils {
	// 直接在本地开Tomcat进行下载
	private String URL_PATH = "http://127.0.0.1:8080/load/aa.jpg";
	public InputStream getInputStream() {
		InputStream inputStream = null;
		HttpURLConnection conn = null;
		try {
			// 连接网络
			URL url = new URL(URL_PATH);
			// 获得HttpURLConnection对象
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			// 设置读取超时时间
			conn.setReadTimeout(3000);
			// 设置连接超时时间
			conn.setConnectTimeout(3000);
			// 设置连接方式
			conn.setRequestMethod("GET");
			// 获得返回code
			int code = conn.getResponseCode();
			// 如果返回ok
			if (code == 200) {
				inputStream = conn.getInputStream();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return inputStream;
	}
	public void saveToDisk() {
		InputStream inputStream = getInputStream();
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream("F://test.jpg");
			byte[] buf = new byte[1024];
			int len = -1;
			while ((len = inputStream.read(buf)) != -1) {
				// 往磁盘写入数据
				fos.write(buf, 0, len);
			}
			fos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
				if (fos != null) {
					fos.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		System.out.println("End");
	}
	public static void main(String[] args) {
		new HttpUtils().saveToDisk();
	}
}

猜你喜欢

转载自moonmonster.iteye.com/blog/2276138