您现在的位置是:首页 > 后台技术 > JavaJava
HttpClient(图文)
第十三双眼睛2020-03-22【Java】人已围观
简介HttpClient使用
httpclient简单使用
1引入依赖
编写代码示例
有的时候,网站会做限制,比如下面这个网站:
http://www.tuicool.com,会出现如下的提示

这时候,只需要添加请求头信息就可以

简单的图片下载
就可以将图片下载到指定位置
如果要使用代理的话,设置如下几行就可以
如果不超时,就可正常访问
设置超时时间
1引入依赖
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> |
public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet get = new HttpGet("http://www.tuicool.com"); CloseableHttpResponse response = httpClient.execute(get); HttpEntity entity = response.getEntity(); String string = EntityUtils.toString(entity,"utf-8"); System.out.println(string); response.close(); httpClient.close(); } |
http://www.tuicool.com,会出现如下的提示

这时候,只需要添加请求头信息就可以

简单的图片下载
public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet get = new HttpGet("http://www.zhaoybbk.com/d/file/p/2019/01-09/6e962e2af6101129845fd4c537f38e93.png"); get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"); CloseableHttpResponse response = httpClient.execute(get); HttpEntity entity = response.getEntity(); if(entity !=null){ String value = entity.getContentType().getValue(); InputStream in = entity.getContent(); FileUtils.copyToFile(in, new File("E://1.png")); } response.close(); httpClient.close(); } |
如果要使用代理的话,设置如下几行就可以
HttpHost proxy = new HttpHost("IP",port); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); get.setConfig(config); |
设置超时时间
RequestConfig config = RequestConfig.custom() .setConnectTimeout(10000) .setSocketTimeout(10000).build(); get.setConfig(config); |
Tags:HttpClient
很赞哦! ()
上一篇:JAVA解析XML
下一篇:redis类型转换异常(图文)