您现在的位置是:首页 > 后台技术 > 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类型转换异常(图文)
相关文章
随机图文
java实现websocket(图文)
WebSocket是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。 在WebSocket API中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。springboot实现不同业务的日志打印到不同的文件中(图文)
这几天有个项目的日志信息比较多,需要把不同业务的日志打印到不同的文件中去,今天在公司搞了很久都没搞定,晚上回来搞,终于搞定了,记录一下。ActiveMQ学习记录(图文)
昨天用了1个下午的时间学习了ActiveMQ东西,为了以后要用的时候方便查询,记录一下。redis类型转换异常(图文)
在开发的过程中,偶然遇到一次将一个对象放入redis,然后取出来,进行类型转换却报错,按道理说不应该,网上查了好多资料都不对,最好找到了答案,记录一下