(三)HttpClient 抓取图片

时间:2023-03-09 17:45:33
(三)HttpClient 抓取图片

第一节: HttpClient 抓取图片

这里pom.xml需要用到io输入输出:

     <dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>

pom.xml 文件:

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javaxk</groupId>
<artifactId>HttpClientTest</artifactId>
<version>0.0.1-SNAPSHOT</version> <dependencies> <dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency> <dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency> </dependencies> </project>
 package com.javaxk.httpclient.chap03;

 import java.io.File;
import java.io.InputStream; import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; public class Demo1 { public static void main(String[] args)throws Exception {
CloseableHttpClient httpClient=HttpClients.createDefault(); // 创建httpClient实例
HttpGet httpGet=new HttpGet("http://www.javaxk.com/templets/javaxk/images/logo.jpg"); // 创建httpget实例
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");
CloseableHttpResponse response=httpClient.execute(httpGet); // 执行http get请求
HttpEntity entity=response.getEntity(); // 获取返回实体
if(entity!=null){
System.out.println("ContentType:"+entity.getContentType().getValue());
InputStream inputStream=entity.getContent();
FileUtils.copyToFile(inputStream, new File("D://logo.jpg"));
}
response.close(); // response关闭
httpClient.close(); // httpClient关闭
} }

运行输出:

ContentType:image/jpeg

D盘下会有一个logo.jpg的图片