• (三)HttpClient 抓取图片


    第一节: 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的图片 

  • 相关阅读:
    C# html转mht
    前端插件
    通过GhostDoc实现自定义方法概要(summary)
    使用word模板生成pdf文件
    js 二维码
    POST 请求静态文件 响应405
    Notepad++ 两个格式化插件
    朴素的标题:MVC中权限管理实践
    对于api安全性的思考
    RSA私钥加密公钥解密、各种密钥格式转换
  • 原文地址:https://www.cnblogs.com/wishwzp/p/7059042.html
Copyright © 2020-2023  润新知