HttPclient 以post方式发送json

使用HttpClient 以POST的形式发送json字符串
步骤:
1.url 、parameters
2.创建httpClient对象
3.创建HttpPost对象
4.为post对象设置参数
5.将参数以实体的实行放入post对象中
6.client.execute(post);返回response对象
7.通过response对象获取响应码,
8.获得结果实体


public void HttpClientPostByJson(){
String url = "http://localhost:8080/../../";
String param = "{\"endTxnDate\":\"20151114\",\"merchId\":\"\",\"sendTime\":\"201510132012123\",\"startTxnDate\":\"20151111\"}";
//创建client和post对象
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
//json形式
post.addHeader("content-type", "application/json;charset=utf-8");
post.addHeader("accept","application/json");
//json字符串以实体的实行放到post中
post.setEntity(new StringEntity(param,Charset.forName("utf-8")));
HttpResponse response = null;
try {
//获得response对象
response = client.execute(post);
} catch (Exception e) {
e.printStackTrace();
}

if(HttpStatus.SC_OK!=response.getStatusLine().getStatusCode()){
System.out.println("请求返回不正确");
}

String result="";
try {
//获得字符串形式的结果
result = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(result);

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值