当前位置:首页 > 安卓游戏 > 动作冒险 > 正文
CloseableHttpClient(httpclient.jar) 动作冒险

CloseableHttpClient(httpclient.jar)

12个月前 (05-20) 类别:动作冒险

  • 发布日期:2025-05-06 03:19:09
  • 所属类别:动作冒险
  • 下载人数:587
  • 版本:
  • 大小:

立即下载

扫二维码手机浏览

CloseableHttpClient(httpclient.jar)介绍

使用java开源工具httpclient怎么使用

使用java开源工具httpClient及jsoup抓取解析网页数据

来源:iteye,原文

CloseableHttpClient(httpclient.jar)

今天做项目的时候遇到这样一个需求,需要在网页上展示今日黄历信息,数据格式如下

公历时间:2016年04月11日星期一

农历时间:猴年三月初五

CloseableHttpClient(httpclient.jar)

天干地支:丙申年壬辰月癸亥日

宜:求子祈福开光祭祀安床

忌:玉堂(黄道)危日,忌出行

主要包括公历/农历日期,以及忌宜信息的等。但是手里并没有现成的数据可供使用,怎么办呢?革命前辈曾经说过,没有枪,没有炮,敌(wang)人(luo)给我们造!网络上有很多现成的在线万年历应用可供使用,虽然没有现成接口,但是我们可以伸出手来,自己去拿。也就是所谓的数据抓取。

这里介绍两个使用的工具,httpClient以及jsoup,简介如下:

HttpClient是ApacheJakartaCommon下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如ApacheJakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。

httpClient使用方法如下:

1.创建HttpClient对象。

2.创建请求方法的实例,并指定请求URL。

3.调用HttpClient对象的execute(HttpUriRequestrequest)发送请求,该方法返回一个HttpResponse。

4.调用HttpResponse相关方法获取相应内容。

5.释放连接。

jsoup是一款Java的HTML解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于jQuery的操作方法来取出和操作数据。

需要更多信息可以参见官网下载地址

httpClient:

jsoup:

接下来我们直接上代码,这里我们抓取2345在线万年历的数据

首先我们定义一个实体类Almanac来存储黄历数据

Almanac.java1packagecom.likx.picker.util.bean;2

3/**4

*万年历工具实体类5

*

6

*@author溯源blog7

*2016年4月11日8

*/9publicclassAlmanac{10

privateStringsolar;

/*阳历e.g.2016年4月11日星期一*/11

privateStringlunar;

/*阴历e.g.猴年三月初五*/12

privateStringchineseAra;

/*天干地支纪年法e.g.丙申年壬辰月癸亥日*/13

privateStringshould;

/*宜e.g.求子祈福开光祭祀安床*/14

privateStringavoid;

/*忌e.g.玉堂(黄道)危日,忌出行*/1516

publicStringgetSolar(){17

returnsolar;18

}1920

publicvoidsetSolar(Stringdate){21

this.solar=date;22

}2324

publicStringgetLunar(){25

returnlunar;26

}2728

publicvoidsetLunar(Stringlunar){29

this.lunar=lunar;30

}3132

publicStringgetChineseAra(){33

returnchineseAra;34

}3536

publicvoidsetChineseAra(StringchineseAra){37

this.chineseAra=chineseAra;38

}3940

publicStringgetAvoid(){41

returnavoid;42

}4344

publicvoidsetAvoid(Stringavoid){45

this.avoid=avoid;46

}4748

publicStringgetShould(){49

returnshould;50

}5152

publicvoidsetShould(Stringshould){53

this.should=should;54

}5556

publicAlmanac(Stringsolar,Stringlunar,StringchineseAra,Stringshould,57

Stringavoid){58

this.solar=solar;59

this.lunar=lunar;60

this.chineseAra=chineseAra;61

this.should=should;62

this.avoid=avoid;63

}64}

然后是抓取解析的主程序,写程序之前需要在官网下载需要的jar包

AlmanacUtil.javapackagecom.likx.picker.util;importjava.io.IOException;importjava.text.SimpleDateFormat;importjava.util.Calendar;importjava.util.Date;importorg.apache.http.HttpEntity;importorg.apache.http.ParseException;importorg.apache.http.client.ClientProtocolException;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClients;importorg.apache.http.util.EntityUtils;importorg.jsoup.Jsoup;importorg.jsoup.nodes.Document;importorg.jsoup.nodes.Element;importorg.jsoup.select.Elements;/***<STRONG>类描述</STRONG>:

2345万年历信息爬取工具<p>*

*@version1.0<p>*@author溯源blog*

*<STRONG>创建时间</STRONG>:2016年4月11日下午14:15:44<p>*<STRONG>修改历史</STRONG>:<p>*<pre>*修改人

修改时间

修改内容*---------------

-------------------

-----------------------------------*</pre>*/publicclassAlmanacUtil{

/**

*单例工具类

*/

privateAlmanacUtil(){

}

/**

*获取万年历信息

*@return

*/

publicstaticAlmanacgetAlmanac(){

Stringurl="";

Stringhtml=pickData(url);

Almanacalmanac=****yzeHTMLByString(html);

returnalmanac;

}

/*

*爬取网页信息

*/

privatestaticStringpickData(Stringurl){

CloseableHttpClienthttpclient=HttpClients.createDefault();

try{

HttpGethttpget=newHttpGet(url);

CloseableHttpResponseresponse=httpclient.execute(httpget);

try{

//获取响应实体

HttpEntityentity=response.getEntity();

//打印响应状态

if(entity!=null){

returnEntityUtils.toString(entity);

}

}finally{

response.close();

}

}catch(ClientProtocolExceptione){

e.printStackTrace();

}catch(ParseExceptione){

e.printStackTrace();

}catch(IOExceptione){

e.printStackTrace();

}finally{

//关闭连接,释放资源

try{

httpclient.close();

}catch(IOExceptione){

e.printStackTrace();

}

}

returnnull;

}

/*

*使用jsoup解析网页信息

*/

privatestaticAlmanac****yzeHTMLByString(Stringhtml){

StringsolarDate,lunarDate,chineseAra,should,avoid="";

Documentdocument=Jsoup.parse(html);

//公历时间

solarDate=getSolarDate();

//农历时间

ElementeLunarDate=document.getElementById("info_nong");

lunarDate=eLunarDate.child(0).html().substring(1,3)+eLunarDate.html().substring(11);

//天干地支纪年法

ElementeChineseAra=document.getElementById("info_chang");

chineseAra=eChineseAra.text().toString();

//宜

should=getSuggestion(document,"yi");

//忌

avoid=getSuggestion(document,"ji");

Almanacalmanac=newAlmanac(solarDate,lunarDate,chineseAra,should,avoid);

returnalmanac;

}

/*

*获取忌/宜

*/

privatestaticStringgetSuggestion(Documentdoc,Stringid){

Elementelement=doc.getElementById(id);

Elementselements=element.getElement**yTag("a");

StringBuffer**=newStringBuffer();

for(Elemente:elements){

**.append(e.text()+"");

}

return**.toString();

}

/*

*获取公历时间,用yyyy年MM月dd日EEEE格式表示。

*@returnyyyy年MM月dd日EEEE

*/

privatestaticStringgetSolarDate(){

Calendarcalendar=Calendar.getInstance();

DatesolarDate=calendar.getTime();

SimpleDateFormatformatter=newSimpleDateFormat("yyyy年MM月dd日EEEE");

returnformatter.format(solarDate);

}}

为了简单明了我把抓取解析抽象成了几个独立的方法,

其中pickData()方法使用httpClient来抓取数据到一个字符串中(就是在网页上点击查看源代码看到的HTML源码),****yzeHTMLByString()方法来解析抓取到的字符串,getSuggestion方法把抓取方法类似的宜忌数据抽象到了一起,另外因为公历时间可以很容易的自己生成就没有在网页上爬取。

然后下面是一个测试类简单测试下效果:AlmanacUtilTest.javapackagecom.likx.picker.util.test;publicclassAlmanacUtilTest{

publicstaticvoidmain(Stringargs[]){

Almanacalmanac=AlmanacUtil.getAlmanac();

System.out.println("公历时间:"+almanac.getSolar());

System.out.println("农历时间:"+almanac.getLunar());

System.out.println("天干地支:"+almanac.getChineseAra());

System.out.println("宜:"+almanac.getShould());

System.out.println("忌:"+almanac.getAvoid());

}}

运行结果如下:

集成到实际项目中效果是这样的:

另外最近博客一直没怎么更新,因为最近考虑到技术氛围的原因,离开了对日外包行业,前往一家互联网公司就职。说一下最近的感受,那就是一个程序员最核心的竞争力不是学会了多少框架,掌握多少种工具(当然这些对于程序员也不可或缺),而是扎实的基础以及快速学习的能力,比如今天这个项目,从对httpClient,jsoup工具一无所知到编写出Demo代码总计大概1个多小时,在之前对于我来说是不可想象的,在技术氛围浓厚的地方快速get技能的感觉,非常好。

当然本例只是一个非常浅显的小例子,网页上内容也很容易抓取,httpClient及jsoup工具更多强大的地方没有体现到,比如httpClient不仅可以发送get请求,而且可以发送post请求,提交表单,传送文件,还比如jsoup最强大的地方在于它支持仿jquery的选择器。本例仅仅使用了最简单的document.getElementById()匹配元素,实际上jsoup的选择器异常强大,可以说它就是java版的jquery,比如这样:Elementslinks=doc.select("a[href]");//awithhrefElementspngs=doc.select("img[src$=.png]");

//imgwithsrcending.pngElementmasthead=doc.select("div.masthead").first();

//divwithclass=mastheadElementsresultLinks=doc.select("h3.r>a");//directaafterh3

Java中的httpclient4.5应该怎么使用

一、所需要的jar包

httpclient-4.5.jar

httpcore-4.4.1.jar

httpmime-4.5.jar

二、实例

Java代码

package cn.tzz.apache.httpclient;

import java.io.File;

import java.io.IOException;

import java.net.URL;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import org.apache.http.HttpEntity;

import org.apache.http.NameValuePair;

import org.apache.http.client.config.RequestConfig;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.conn.ssl.DefaultHostnameVerifier;

import org.apache.http.conn.util.PublicSuffixMatcher;

import org.apache.http.conn.util.PublicSuffixMatcherLoader;

import org.apache.http.entity.ContentType;

import org.apache.http.entity.StringEntity;

import org.apache.http.entity.mime.MultipartEntityBuilder;

import org.apache.http.entity.mime.content.FileBody;

import org.apache.http.entity.mime.content.StringBody;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.util.EntityUtils;

public class HttpClientUtil{

private RequestConfig requestConfig= RequestConfig.custom()

.setSocketTimeout(15000)

.setConnectTimeout(15000)

.setConnectionRequestTimeout(15000)

.build();

private static HttpClientUtil instance= null;

private HttpClientUtil(){}

public static HttpClientUtil getInstance(){

if(instance== null){

instance= new HttpClientUtil();

}

return instance;

}

/**

*发送 post请求

*@param httpUrl地址

*/

public String sendHttpPost(String httpUrl){

HttpPost httpPost= new HttpPost(httpUrl);//创建httpPost

return sendHttpPost(httpPost);

}

/**

*发送 post请求

*@param httpUrl地址

*@param params参数(格式:key1=value1&key2=value2)

*/

public String sendHttpPost(String httpUrl, String params){

HttpPost httpPost= new HttpPost(httpUrl);//创建httpPost

try{

//设置参数

StringEntity stringEntity= new StringEntity(params,"UTF-8");

stringEntity.setContentType("application/x-www-form-urlencoded");

httpPost.setEntity(stringEntity);

} catch(Exception e){

e.printStackTrace();

}

return sendHttpPost(httpPost);

}

/**

*发送 post请求

*@param httpUrl地址

*@param maps参数

*/

public String sendHttpPost(String httpUrl, Map<String, String> maps){

HttpPost httpPost= new HttpPost(httpUrl);//创建httpPost

//创建参数队列

List<NameValuePair> nameValuePairs= new ArrayList<NameValuePair>();

for(String key: maps.keySet()){

nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));

}

try{

httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));

} catch(Exception e){

e.printStackTrace();

}

return sendHttpPost(httpPost);

}

/**

*发送 post请求(带文件)

*@param httpUrl地址

*@param maps参数

*@param fileLists附件

*/

public String sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists){

HttpPost httpPost= new HttpPost(httpUrl);//创建httpPost

MultipartEntityBuilder meBuilder= MultipartEntityBuilder.create();

for(String key: maps.keySet()){

meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));

}

for(File file: fileLists){

FileBody fileBody= new FileBody(file);

meBuilder.addPart("files", fileBody);

}

HttpEntity reqEntity= meBuilder.build();

httpPost.setEntity(reqEntity);

return sendHttpPost(httpPost);

}

/**

*发送Post请求

*@param httpPost

*@return

*/

private String sendHttpPost(HttpPost httpPost){

CloseableHttpClient httpClient= null;

CloseableHttpResponse response= null;

HttpEntity entity= null;

String responseContent= null;

try{

//创建默认的httpClient实例.

httpClient= HttpClients.createDefault();

httpPost.setConfig(requestConfig);

//执行请求

response= httpClient.execute(httpPost);

entity= response.getEntity();

responseContent= EntityUtils.toString(entity,"UTF-8");

} catch(Exception e){

e.printStackTrace();

} finally{

try{

//关闭连接,释放资源

if(response!= null){

response.close();

}

if(httpClient!= null){

httpClient.close();

}

} catch(IOException e){

e.printStackTrace();

}

}

return responseContent;

}

/**

*发送 get请求

*@param httpUrl

*/

public String sendHttpGet(String httpUrl){

HttpGet httpGet= new HttpGet(httpUrl);//创建get请求

return sendHttpGet(httpGet);

}

/**

*发送 get请求Https

*@param httpUrl

*/

public String sendHttpsGet(String httpUrl){

HttpGet httpGet= new HttpGet(httpUrl);//创建get请求

return sendHttpsGet(httpGet);

}

/**

*发送Get请求

*@param httpPost

*@return

*/

private String sendHttpGet(HttpGet httpGet){

CloseableHttpClient httpClient= null;

CloseableHttpResponse response= null;

HttpEntity entity= null;

String responseContent= null;

try{

//创建默认的httpClient实例.

httpClient= HttpClients.createDefault();

httpGet.setConfig(requestConfig);

//执行请求

response= httpClient.execute(httpGet);

entity= response.getEntity();

responseContent= EntityUtils.toString(entity,"UTF-8");

} catch(Exception e){

e.printStackTrace();

} finally{

try{

//关闭连接,释放资源

if(response!= null){

response.close();

}

if(httpClient!= null){

httpClient.close();

}

} catch(IOException e){

e.printStackTrace();

}

}

return responseContent;

}

/**

*发送Get请求Https

*@param httpPost

*@return

*/

private String sendHttpsGet(HttpGet httpGet){

CloseableHttpClient httpClient= null;

CloseableHttpResponse response= null;

HttpEntity entity= null;

String responseContent= null;

try{

//创建默认的httpClient实例.

PublicSuffixMatcher publicSuffixMatcher= PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));

DefaultHostnameVerifier hostnameVerifier= new DefaultHostnameVerifier(publicSuffixMatcher);

httpClient= HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();

httpGet.setConfig(requestConfig);

//执行请求

response= httpClient.execute(httpGet);

entity= response.getEntity();

responseContent= EntityUtils.toString(entity,"UTF-8");

} catch(Exception e){

e.printStackTrace();

} finally{

try{

//关闭连接,释放资源

if(response!= null){

response.close();

}

if(httpClient!= null){

httpClient.close();

}

} catch(IOException e){

e.printStackTrace();

}

}

return responseContent;

}

}

java中如何安装.jar包

JAVA为我们提供了大量基础 jar包,但在实际开发中,经常还需要引入第三方 jar包,比如做 HTTP操作时的 HttpClient jar包,那如何将第三方 jar包引入到自己的工程中呢?\x0d\x0a步骤一:在工程上右键"New"-->"Folder"新建一个名称为 lib的文件夹,并将第三方 jar包全部拷贝到这个目录下!\x0d\x0a\x0d\x0a步骤二:在工程上右键"Build Path"-->"Configure Build Path...";\x0d\x0a1>在新打开的窗口中点击右侧按钮"Add Library",打开"Add Library"窗口;\x0d\x0a2>在弹出窗口中选择"User Library",点击"Next";\x0d\x0a3>在弹出窗口中继续点击"User Libraries...";\x0d\x0a4>在弹出窗口中继续点击"New...";\x0d\x0a5>在弹出窗口中输入 User Library的名称"HttpClientJars",点击"OK";\x0d\x0a6>在回到的窗口中,选择刚才创建的项“HttpClientJars”,点击"Add JARs";\x0d\x0a7>在弹出的窗口中,找到我们的工程,选中我们拷贝到 lib目录下的所有 jar文件,点击"OK";\x0d\x0a8>回到“Add Library”窗口,在 User Library列表中选择刚刚创建的"HttpClientJars",点击"Finish";\x0d\x0a9>关闭所有窗口,添加完毕。 \x0d\x0a步骤四:总结\x0d\x0a这是添加第三方 jar包通用的方法,根据这个方法,我们可以把需要的所有第三方 jar包以一种很干净整洁的方式添加到工程中!\x0d\x0a关于经验中涉及的 HttpClient jar包

版权说明:如非注明,本站文章均为 皮努努下载 原创,转载请注明出处和附带本文链接;

本文地址:https://www.pinunu.com/dongzuo/closeablehttpclienthttpcl.html