HttpClient的Post请求数据

最近在项目中需要添加Post请求数据,以前的Get请求是使用JDK自带的URLConnection。在项目组人员的推荐下,开始使用HttpClient。

HttpClient简介:

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,

并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus

和HTMLUnit都使用了HttpClient。

HttpClient发送请求的步骤:

(1)创建HttpClient对象。

(2)创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。

(3) 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,

         也可调用setEntity(HttpEntity entity)方法来设置请求参数。

(4)调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。

(5)调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法

         可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

(6) 释放连接。无论执行方法是否成功,都必须释放连接

因此,接下来按照该步骤,编写Post请求代码如下:

public String doPost(String url, Map<String,String> map, String charset){
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try{
httpClient = HttpClients.createDefault();
httpPost = new HttpPost(url);
//设置参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String,String> elem = (Map.Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
}
if(list.size() > 0){
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity,charset);
}
}
}catch(Exception ex){
ex.printStackTrace();
}
return result;
}

测试代码如下:

    public static void main(String[] args) throws UnsupportedEncodingException {
String url = "http://admin.tingwen.me/index.php/api/interfaceXykj/touList";
Map<String,String> params = new HashMap<>();
params.put("page","100");
HttpClient client = new HttpClient();
String result = client.doPost(url,params,"UTF-8");
System.out.println(UnicodeToString(result));
}

测试结果:

{
     "status": 1,
     "msg": "查询头条新闻成功!",
     "results": [
           {
                  "id": "65678",
                  "tuiid": "0",
                  "post_author": "8909",
                  "post_news": "161",
                  "author": "0",
                  "post_keywords": "Snap,无人机,科技",
                  "post_date": "2017-03-03 16:19:43",
                  "post_times": "",
                  "post_content": "",
                  "post_title": "传Snap公司正研发无人机:贯彻公司理念",
                  "post_lai": "新浪科技",
                  "post_mp": "http://mp3.tingwen.me/data/upload/mp3/58b9270c35694.mp3",
                  "post_time": "105000",
                  "post_size": "1268345"
           }
       ]
}


原文地址:https://www.cnblogs.com/junjiang3/p/7281753.html