对于HttpClient的介绍和使用可以登录官网查看 http://hc.apache.org/httpclient-3.x/
准备:将图片文件夹放置在tomcat的ROOT目录下,可参考一下路径
F:\黑马297\Java开发工具\tomcat\apache-tomcat-7.0.79\webapps\ROOT
之后启动tomcat
public class HttpClientTest {
private static String url = "http://localhost:8080/meinv/meinv1.jpg";
public static void main(String[] args) throws Exception {
// 创建一个java代码的浏览器
HttpClient client = new HttpClient();
// 创建get请求实例
GetMethod method = new GetMethod(url);
// 执行请求
int responseStatus = client.executeMethod(method);
//HttpStatus http状态代码的常量
if(HttpStatus.SC_OK != responseStatus){
throw new RuntimeException("服务器响应错误");
}
// 获取服务器response的数据
byte[] responseBody = method.getResponseBody();
File file = new File("meinv1.jpg");
FileOutputStream fos = new FileOutputStream(file);
fos.write(responseBody);
fos.close();
// 释放链接
method.releaseConnection();
}
}
执行完之后: