作者:手机用户2502859707 | 来源:互联网 | 2023-05-18 12:08
Http协议的重要性这里不多介绍,基于上一篇介绍Http请求的GET和POST方式,这篇继续用Httpclient通过post方式来实现Http请求。先简单介绍一下Httpclient。Httpcli
Http协议的重要性这里不多介绍,基于上一篇介绍Http请求的GET和POST方式,这篇继续用Httpclient通过post方式来实现Http请求。先简单介绍一下Httpclient。Httpclient相比传统JDK自带的URL Connection增加了易用性和灵活性,它支持Http协议,提供了功能丰富的工具包,不仅让客户端发送Http请求变得容易,而且也提高了开发人员的开发效率。
下面重点介绍一下使用方法,首先,pom文件
org.apache.httpcomponents
httpclient
4.3.6
commons-logging
commons-logging
1.2
net.sf.json-lib
json-lib
2.4
jdk15
commons-lang
commons-lang
2.5
commons-beanutils
commons-beanutils
1.9.2
commons-collections
commons-collections
3.2.1
具体代码如下:
public class HttpclientDemo {
public List getDemoList(String demoName, String demoStatus){
List resultList = new ArrayList();
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpRespOnse= null;
//URL
String url = "http://192.168.0.1/httpclientDemo/service/getDemoList.do";
//封装请求参数
List params = Lists.newArrayList();
params.add(new BasicNameValuePair("demoName", demoName));
params.add(new BasicNameValuePair("demoStatus", demoStatus));
try{
//转换键值对
String str = EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
//创建请求--get
HttpGet httpGet = new HttpGet(url+"?"+str);
httpRespOnse= httpClient.execute(httpGet);
//判断状态码
if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//解析结果
String result = EntityUtils.toString(httpResponse.getEntity());
JSONArray jsOnArray= JSONArray.fromObject(result);
resultList = JSONArray.toList(jsonArray, new DemoTypeEntity(), new JsonConfig());
}
//释放连接
httpResponse.close();
}catch(Exception e){
e.printStackTrace();
}
return resultList;
}
}
具体的调用过程如下:
1.创建CloseableHttpClient对象
2.设置请求参数
3.创建请求方法的实例,如果需要发送GET请求则创建HttpGet对象,如果需要发送POST请求则创建HttpPost对象,我们这里创建的是HttpGet对象
4.指定URL
5.设置头信息
6.调用CloseableHttpClient对象的execute方法,返回一个CloseableHttpResponse对象
解析结果时需要注意,通过调用CloseableHttpClient对象的execute方法,返回一个CloseableHttpResponse对象,返回的对象调用getEntity方法可获取HttpEntity对象,该对象包含了服务器的响应内容