httpclient post json 格式传参

/**
* 获取用户统计数据(目睹的数据统计)

* @author fuyongjin 2018-1-17
* @param url
* @param filter
*            1 表示查看观看直播时间长于1分钟的用户,0 表示所有
* @param headreq
* @param pageNum
*            页面 默认1 (默认每页数据20条)
* @return
*/
public static HttpStrBean doPost(String url, JsonObject requestBody, Map<String, String> headreq) {
HttpStrBean bean = new HttpStrBean();
bean.setSuccess(false);
if (StringUtil.isEmpty(url)) {
bean.setMsg("url链接为空");
return bean;
}


org.apache.http.client.HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url); // post方法
try {
// 遍历便捷请求头
for (Map.Entry<String, String> entry : headreq.entrySet()) {
method.setHeader(entry.getKey(), entry.getValue());


}
StringEntity entity = new StringEntity(requestBody.toString(),
Charset.forName("UTF-8"));
method.setEntity(entity);
HttpResponse result = client.execute(method); // 执行请求


/** 请求发送成功,并得到响应 **/
if (result.getStatusLine().getStatusCode() == 200) {

/** 读取服务器返回过来的json字符串数据 **/
String str = EntityUtils.toString(result.getEntity());
bean.setResult(str); // 以字符串的形式返回结果
bean.setMsg("200");
bean.setSuccess(true);
return bean;

} else {
bean.setMsg("200 errcode: "
+ result.getStatusLine().getStatusCode());
return bean;
}
} catch (URIException e) {
// log.error("执行HTTP Get请求时,编码查询字符串“" + queryString + "”发生异常!", e);
bean.setMsg(e.getMessage());
} catch (IOException e) {
// log.error("执行HTTP Get请求" + url + "时,发生异常!", e);
bean.setMsg(e.getMessage());
} finally {
method.releaseConnection();
}
return bean;
}


public static void main(String[] args) {
// String url = "http://api.mudu.tv/v1/activities";
String url = "http://api.mudu.tv/v1/activities/95392/visitors";
Map<String, String> headreq = new HashMap<String, String>();
headreq.put("Authorization", "Bearer 4kzmkwxtbaw2ja95gq5d629wxvwcmsej");
headreq.put("Content-Type", "application/json");


JsonObject json = new JsonObject();
json.addProperty("filter", 0);
json.addProperty("perPage", 5);
json.addProperty("p", 1);


HttpStrBean httpStrBean = doPost(url, json, headreq);
String result = httpStrBean.getResult();
List<VLiveUserCount> parseObject = JSONObject.parseArray(
httpStrBean.getResult(), VLiveUserCount.class);
System.out.println(parseObject.size());
System.out.println(result);


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值