HttpClient--入门
来源:互联网 发布:牵引变电所接地网优化 编辑:程序博客网 时间:2024/05/17 09:36
1 获取网页代码
public static void main(String[] args){ CloseableHttpClient httpClient = HttpClients.createDefault();//创建httpclient实例 HttpGet httpGet=new HttpGet("http://www.open1111.com"); CloseableHttpResponse response=null; try { response= httpClient.execute(httpGet); } catch (ClientProtocolException e) {//协议异常 e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } HttpEntity entity=response.getEntity(); try { String string = EntityUtils.toString(entity,"utf-8"); System.out.println(string); } catch (ParseException e) {//解析异常 e.printStackTrace(); } catch (IOException e) {//IO异常 e.printStackTrace(); } try { response.close(); httpClient.close(); } catch (IOException e) { e.printStackTrace(); } }
2 获取相关信息
2.1 获取返回的状态信息:
CloseableHttpResponse response = httpClient.execute(httpGet);System.out.println("Status:"+response.getStatusLine().getStatusCode());
2.2 获取返回头信息中ContentType的值
System.out.println(entity.getContentType().getValue());
摘自:http://www.open1111.com
3 获取图片
public static void main(String[] args) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault();// 创建httpclient实例 HttpGet httpGet = new HttpGet("https://www.baidu.com/img/bd_logo1.png"); //设置请求头信息User-Agent模拟浏览器 httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; W…) Gecko/20100101 Firefox/56.0"); CloseableHttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if(entity!=null){ System.out.println("ContentType:"+entity.getContentType().getValue()); InputStream content = entity.getContent(); //复制文件到本地 //org.codehaus.plexus.util.FileUtils.copyURLToFile(new URL("https://www.baidu.com/img/bd_logo1.png"), new File("D:/image.png")); FileUtils.copyToFile(content,new File("D:/image.png")); } response.close(); httpClient.close(); System.out.println("run over"); }
阅读全文
0 0
- HttpClient入门
- HttpClient入门
- httpClient入门
- HTTPClient入门
- HttpClient入门
- HttpClient入门
- HttpClient入门
- HttpClient入门
- HttpClient入门
- HttpClient入门
- HttpClient入门
- HttpClient入门
- HttpClient入门
- HttpClient入门
- HttpClient入门
- HttpClient入门 .
- HttpClient入门
- HttpClient入门
- 计算机内存清理
- nopCommerce创建实体服务接口与实体服务类
- 动态规划的经典问题初探: Best Time to Buy and Sell Stock(DP)
- 双十一快到了,剁手党们准备好了吗,快来看看优惠卷商城吧
- Java Security Architecture--Java安全体系技术文档翻译(二)
- HttpClient--入门
- 彻底理解android 建造者模式
- 【算法】常用算法之快速排序算法
- 由Mybatis发现的一个坑
- Mac截图
- 一个18届程序媛的offer血泪史
- CSRF XSS(XSRF) CORS OPTIONS(HTTP)概念理解
- 笔记_计算机网络_Python socket编程
- 代理模式