首先打开myEclipse创建一个web项目,然后将我们要访问的图片资源放在WEBRoot文件夹先,然后将项目部署在Tomcate服务器上,再者就是启动服务器。
然后再eclipse中创建一个普通的java项目,模仿客户端,使用Http协议的Get方法访问图片资源,具体代码如下:
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;