http協議訪問網絡資源圖片---GET方法

首先打開myEclipse建立一個web項目,而後將咱們要訪問的圖片資源放在WEBRoot文件夾先,而後將項目部署在Tomcate服務器上,再者就是啓動服務器。 java


而後再eclipse中建立一個普通的java項目,模仿客戶端,使用Http協議的Get方法訪問圖片資源,具體代碼以下: web

package com.http.get;

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;




public class HttpUtils {

	// 本地的IP地址是169.254.74.214
	private static String URL_PATH = "http://169.254.167.66:8080/myhttp/yuliyan.png";

	public HttpUtils() {

	}

	public static void saveImageToDisk() {
		InputStream inputStream = getInputStream();
		byte[] data = new byte[1024];
		FileOutputStream fileOutputStream = null;
		int len = 0;
		try {
			fileOutputStream = new FileOutputStream("c:\\oue.jpg");
			while ((len = inputStream.read()) != -1) {
				fileOutputStream.write(data, 0, len);
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fileOutputStream != null) {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public static InputStream getInputStream() {
		InputStream inputStream = null;
		HttpURLConnection httpsURLConnection = null;
		try {
			URL url = new URL(URL_PATH);

			if (url != null) {
				httpsURLConnection = (HttpURLConnection) url.openConnection();
				httpsURLConnection.setConnectTimeout(3000); // 設置網絡的超時時間
				httpsURLConnection.setRequestMethod("GET"); // 設置本次http請求使用GET方式
				int responseCode = httpsURLConnection.getResponseCode();
				if (responseCode == 200) {
					// 從服務器端獲得輸入流
					inputStream = httpsURLConnection.getInputStream();
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return inputStream;
	}

	public static void main(String[] args) {
		// 從服務器得到圖片完成保存圖片在本地
		saveImageToDisk();
	}

}
注意: 咱們在建立客戶端訪問服務器端得代碼中要先將commons-httpclient-3.0.1.jar導入帶項目中,而後再建立java類,同時要注意在敲
HttpURLConnection httpsURLConnection = null;
		try {
			URL url = new URL(URL_PATH);

			if (url != null) {
				httpsURLConnection = (HttpURLConnection) url.openConnection();
				httpsURLConnection.setConnectTimeout(3000); // 設置網絡的超時時間
				httpsURLConnection.setRequestMethod("GET"); // 設置本次http請求使用GET方式
				int responseCode = httpsURLConnection.getResponseCode();
這段代碼時不要導javax.net.ssl.HttpsURLConnection,要導入import java.net.HttpURLConnection;



,疑問:我在運行完畢上述代碼以後發如今c盤下的圖片資源存在,可是看不了,對比服務器端得圖片大小是18008字節,而本地圖片大小卻達到了14163368字節,這讓我很是費解,但願高手們能給我指點迷津

相關文章
相關標籤/搜索