您现在的位置是:首页 > 后台技术 > JavaJava
HttpClient(图文)
第十三双眼睛2020-03-22【Java】人已围观
简介HttpClient使用
httpclient简单使用
1引入依赖
编写代码示例
有的时候,网站会做限制,比如下面这个网站:
http://www.tuicool.com,会出现如下的提示
![](/d/file/p/2021/01-05/00ad4d977315cd721f5bfd1e5fb05c88.jpg)
这时候,只需要添加请求头信息就可以
![](/d/file/p/2021/01-05/85ccc2af3fd4572476ee3fe4a5247d28.jpg)
简单的图片下载
就可以将图片下载到指定位置
如果要使用代理的话,设置如下几行就可以
如果不超时,就可正常访问
设置超时时间
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,会出现如下的提示
![](/d/file/p/2021/01-05/00ad4d977315cd721f5bfd1e5fb05c88.jpg)
这时候,只需要添加请求头信息就可以
![](/d/file/p/2021/01-05/85ccc2af3fd4572476ee3fe4a5247d28.jpg)
简单的图片下载
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类型转换异常(图文)
相关文章
随机图文
彻底搞懂字符编码(图文)
彻底搞懂字符编码shiro学习(图文)
Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理。使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序封装系统配置参数工具类(图文)
以前记得有一个方法可以把配置文件中的配置信息读取到一个类中,这样在项目里用的时候就会很方便了,但是不记得怎么写了,今天特意找了找资料,记录下来,以后想用的化,直接来这里看就好java实现websocket(图文)
WebSocket是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。 在WebSocket API中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。