httpClient对请求回来的response.getEntity()中的contentType和图片后缀进行比较判断
这样就能下载我们想要的类型的图片了
@Test
public void testGetDownloadPicture() {
/**
*@param: []
*@return: void
*@description: 下载图片
*/
String url_str = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic15.nipic.com%2F20110811%2F8029346_082444436000_2.jpg&refer=http%3A%2F%2Fpic15.nipic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1636111937&t=c133a2ec6bef5ad21ce34161aebc3948";
//可关闭的httpclient客户端,相当于你打开一个浏览器
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
//构造httpget请求对象
HttpGet httpGet = new HttpGet(url_str);
//响应
CloseableHttpResponse response = null;
try {
response = closeableHttpClient.execute(httpGet);
//获取响应结果 HttpEntity不仅可以作为结果,也可以作为请求的参数实体,有很多实现
HttpEntity entity = response.getEntity();
// image/jpg image/jpeg image/png
String contentType = entity.getContentType().getValue();//特别注意这里要getValue一下,否则这里不是string类型的数据而是eader类型的
String suffix = ".jpeg";
if (contentType.contains("jpeg") || contentType.contains("jpg")) {
suffix = ".jpg";
} else if (contentType.contains("bmp") || contentType.contains("bitmap")) {
suffix = ".bmp";
} else if (contentType.contains("png")) {
suffix = "png";
} else if (contentType.contains("gif")) {
suffix = "gif";
}
//字节流
byte[] bytes = EntityUtils.toByteArray(entity);
String localpath = "D:\\LDS\\MavenDemoProject\\src\\main\\resources\\" + "我用httpclient的Get方式下载的图片" + suffix;
FileOutputStream fos = new FileOutputStream(localpath);
fos.write(bytes);
//关闭输出流
fos.close();
//对HttpEntity操作的工具类:EntityUtils
//String toStringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8.name());
//System.out.println(toStringResult);
//确保流关闭
EntityUtils.consume(entity);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (closeableHttpClient != null) {
try {
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}