HttPclient 以post方式发送json
2024-09-06 00:56:33
使用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);
- }
最新文章
- 工业串口和网络软件通讯平台(SuperIO 2.0)发布
- 【leetcode】Search in Rotated Sorted Array (hard)
- MySQL慢日志监控脚本实例剖析
- CSS3实现气泡效果
- Error 2147943712 during task creation
- SO_REUSEADDR
- Spring 使用注解方式进行事物管理
- ubuntu下lnmp的安装
- 说说Xcode4中xib绑定的原理
- CodeForces 543A - Writing Code DP 完全背包
- Jquery右击显示菜单事件,运用smartMenu插件。
- PHP简单分页省略中间页码
- 【Webpack的使用指南 01】Webpack入门
- electron 热更新
- redis 系列13 集合对象
- java中对象的创建过程
- Mysql安装、设置密码、编码
- linux下nginx日常操作
- HOWTO: 如何利用Avizo或Amira计算孔隙率(Porosity)
- 最大公约数&;&;最小公倍数