做网站自己买域名,洛阳市App网站开发公司,一键制作网站软件,企业网站制作价格Java教程分享使用HttpClient抓取页面内容#xff0c;使用HttpClient工具来发送Http请求1.简介HttpClient 是 Apache Jakarta Common 下的子项目#xff0c;用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包#xff0c;并且它支持 HTTP 协议最新的版本和…Java教程分享使用HttpClient抓取页面内容使用HttpClient工具来发送Http请求1.简介HttpClient 是 Apache Jakarta Common 下的子项目用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient。HttpClient 相比传统 JDK 自带的 URLConnection增加了易用性和灵活性它不仅是客户端发送 HTTP 请求变得容易而且也方便了开发人员测试接口基于 HTTP 协议的即提高了开发的效率也方便提高代码的健壮性。因此熟练掌握 HttpClient 是很重要的必修内容掌握 HttpClient 后相信对于 HTTP 协议的了解会更加深入。2.应用场景3.HttpClient工具的使用1添加依赖!-- Apache Http Begin --dependency groupIdorg.apache.httpcomponents/groupId artifactIdhttpclient/artifactId version4.5.5/version/dependencydependency groupIdorg.apache.httpcomponents/groupId artifactIdfluent-hc/artifactId version4.5.5/version/dependencydependency groupIdorg.apache.httpcomponents/groupId artifactIdhttpmime/artifactId version4.5.5/version/dependency!-- Apache Http End --2编写测试代码 Testpublic void testHttpClient() throws IOException {//1.获得HttpClient对象 CloseableHttpClient client HttpClients.createDefault();//2.创建请求对象如果是post请求 HttpPost 如果是get请求 HttpGet对象 String uri baidu com; HttpGet get new HttpGet(uri);//3.执行get请求,获得响应消息对象 CloseableHttpResponse response client.execute(get);//4.获取响应行 StatusLine statusLine response.getStatusLine();//5.获取状态码int code statusLine.getStatusCode();if(code200){//响应成功 HttpEntity entity response.getEntity();//6.获取响应体中的内容// InputStream is entity.getContent();// byte[] b new byte[8192];// int len 0;// while((len is.read(b))!-1){// System.out.println(new String(b,0,len));// }// is.close(); System.out.println(EntityUtils.toString(entity, utf-8)); } }