---
title: "HttpClient抓取图片"
author: "andrew7676"
date: "2019-04-16T15:50:18Z"
tags: ["HttpClient"]
categories: ["编程语言"]
slug: "httpclient"
draft: false
lastmod: "2019-04-16T15:50:18Z"
id: 2440148
url: "https://andrew7676.iteye.com/blog/2440148"
---

\[size=medium]\[b]1. HttpClient抓取图片\[/b]\[/size] \[code="说明"] pom.xml 4.0.0 com.andrew HttpClientDemo 0.0.1-SNAPSHOT org.apache.httpcomponents httpclient 4.5.2 commons-io commons-io 2.5 Demo01.java package com.andrew.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 Demo01 { public static void main(String\[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建httpClient实例 HttpGet httpGet = new HttpGet("http://www.pptbz.com/pptpic/UploadFiles\_6909/201203/2012031220134655.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("E://chap03demo01.gif")); } response.close(); // response关闭 httpClient.close(); // httpClient关闭 } } 运行结果： ContentType:image/jpeg \[/code]