第一节: HttpClient 抓取图片
这里pom.xml需要用到io输入输出:
1 <dependency> 2 <groupId>commons-io</groupId> 3 <artifactId>commons-io</artifactId> 4 <version>2.5</version> 5 </dependency>
pom.xml 文件:
1 <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"> 2 <modelVersion>4.0.0</modelVersion> 3 <groupId>com.javaxk</groupId> 4 <artifactId>HttpClientTest</artifactId> 5 <version>0.0.1-SNAPSHOT</version> 6 7 <dependencies> 8 9 <dependency> 10 <groupId>org.apache.httpcomponents</groupId> 11 <artifactId>httpclient</artifactId> 12 <version>4.5.2</version> 13 </dependency> 14 15 <dependency> 16 <groupId>commons-io</groupId> 17 <artifactId>commons-io</artifactId> 18 <version>2.5</version> 19 </dependency> 20 21 </dependencies> 22 23 </project>
1 package com.javaxk.httpclient.chap03; 2 3 import java.io.File; 4 import java.io.InputStream; 5 6 import org.apache.commons.io.FileUtils; 7 import org.apache.http.HttpEntity; 8 import org.apache.http.client.methods.CloseableHttpResponse; 9 import org.apache.http.client.methods.HttpGet; 10 import org.apache.http.impl.client.CloseableHttpClient; 11 import org.apache.http.impl.client.HttpClients; 12 13 public class Demo1 { 14 15 public static void main(String[] args)throws Exception { 16 CloseableHttpClient httpClient=HttpClients.createDefault(); // 创建httpClient实例 17 HttpGet httpGet=new HttpGet("http://www.javaxk.com/templets/javaxk/images/logo.jpg"); // 创建httpget实例 18 httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0"); 19 CloseableHttpResponse response=httpClient.execute(httpGet); // 执行http get请求 20 HttpEntity entity=response.getEntity(); // 获取返回实体 21 if(entity!=null){ 22 System.out.println("ContentType:"+entity.getContentType().getValue()); 23 InputStream inputStream=entity.getContent(); 24 FileUtils.copyToFile(inputStream, new File("D://logo.jpg")); 25 } 26 response.close(); // response关闭 27 httpClient.close(); // httpClient关闭 28 } 29 30 }
运行输出:
ContentType:image/jpeg
D盘下会有一个logo.jpg的图片