您的位置:首页 > 理论基础 > 计算机网络

用Httpclient通过post方式来实现http请求

2017-02-28 17:58 405 查看
Http协议的重要性这里不多介绍,基于上一篇介绍Http请求的GET和POST方式,这篇继续用Httpclient通过post方式来实现Http请求。先简单介绍一下Httpclient。Httpclient相比传统JDK自带的URL Connection增加了易用性和灵活性,它支持Http协议,提供了功能丰富的工具包,不仅让客户端发送Http请求变得容易,而且也提高了开发人员的开发效率。

下面重点介绍一下使用方法,首先,pom文件

<!-- httpClient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
</dependency>

<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<!-- json-lib还需要以下依赖包 -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>具体代码如下:
public class HttpclientDemo {

public List<DemoTypeEntity> getDemoList(String demoName, String demoStatus){
List<String> resultList = new ArrayList<String>();
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
//URL
String url = "http://192.168.0.1/httpclientDemo/service/getDemoList.do";
//封装请求参数
List<NameValuePair> 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对象,该对象包含了服务器的响应内容
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐