首先打開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;