服务器用的是Springmvc,接口内容:

  1. @ResponseBody
  2. @RequestMapping(value="/order",method=RequestMethod.POST)
  3. public boolean order(HttpServletRequest request,@RequestBody List<Order> orders) throws Exception {
  4. AdmPost admPost = SessionUtil.getCurrentAdmPost(request);
  5. if(admPost == null){
  6. throw new RuntimeException("[OrderController-saveOrUpdate()] 当前登陆的用户职务信息不能为空!");
  7. }
  8. try {
  9. this.orderService.saveOrderList(orders,admPost);
  10. Loggers.log("订单管理",admPost.getId(),"导入",new Date(),"导入订单成功,订单信息--> " + GsonUtil.toString(orders, new TypeToken<List<Order>>() {}.getType()));
  11. return true;
  12. } catch (Exception e) {
  13. e.printStackTrace();
  14. Loggers.log("订单管理",admPost.getId(),"导入",new Date(),"导入订单失败,订单信息--> " + GsonUtil.toString(orders, new TypeToken<List<Order>>() {}.getType()));
  15. return false;
  16. }
  17. }

通过ajax访问的时候,代码如下:

  1. $.ajax({
  2. type : "POST",
  3. contentType : "application/json; charset=utf-8",
  4. url : ctx + "order/saveOrUpdate",
  5. dataType : "json",
  6. anysc : false,
  7. data : {orders:[{orderId:"11",createTimeOrder:"2015-08-11"}]},  // Post 方式,data参数不能为空"",如果不传参数,也要写成"{}",否则contentType将不能附加在Request Headers中。
  8. success : function(data){
  9. if (data != undefined && $.parseJSON(data) == true){
  10. $.messager.show({
  11. title:'提示信息',
  12. msg:'保存成功!',
  13. timeout:5000,
  14. showType:'slide'
  15. });
  16. }else{
  17. $.messager.alert('提示信息','保存失败!','error');
  18. }
  19. },
  20. error : function(XMLHttpRequest, textStatus, errorThrown) {
  21. alert(errorThrown + ':' + textStatus); // 错误处理
  22. }
  23. });

通过HttpClient方式访问,代码如下:

    1. package com.ec.spring.test;
    2. import java.io.IOException;
    3. import java.nio.charset.Charset;
    4. import org.apache.commons.logging.Log;
    5. import org.apache.commons.logging.LogFactory;
    6. import org.apache.http.HttpResponse;
    7. import org.apache.http.HttpStatus;
    8. import org.apache.http.client.HttpClient;
    9. import org.apache.http.client.methods.HttpPost;
    10. import org.apache.http.entity.StringEntity;
    11. import org.apache.http.impl.client.DefaultHttpClient;
    12. import org.apache.http.util.EntityUtils;
    13. import com.google.gson.JsonArray;
    14. import com.google.gson.JsonObject;
    15. public class APIHttpClient {
    16. // 接口地址
    17. private static String apiURL = "http://192.168.3.67:8080/lkgst_manager/order/order";
    18. private Log logger = LogFactory.getLog(this.getClass());
    19. private static final String pattern = "yyyy-MM-dd HH:mm:ss:SSS";
    20. private HttpClient httpClient = null;
    21. private HttpPost method = null;
    22. private long startTime = 0L;
    23. private long endTime = 0L;
    24. private int status = 0;
    25. /**
    26. * 接口地址
    27. *
    28. * @param url
    29. */
    30. public APIHttpClient(String url) {
    31. if (url != null) {
    32. this.apiURL = url;
    33. }
    34. if (apiURL != null) {
    35. httpClient = new DefaultHttpClient();
    36. method = new HttpPost(apiURL);
    37. }
    38. }
    39. /**
    40. * 调用 API
    41. *
    42. * @param parameters
    43. * @return
    44. */
    45. public String post(String parameters) {
    46. String body = null;
    47. logger.info("parameters:" + parameters);
    48. if (method != null & parameters != null
    49. && !"".equals(parameters.trim())) {
    50. try {
    51. // 建立一个NameValuePair数组,用于存储欲传送的参数
    52. method.addHeader("Content-type","application/json; charset=utf-8");
    53. method.setHeader("Accept", "application/json");
    54. method.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));
    55. startTime = System.currentTimeMillis();
    56. HttpResponse response = httpClient.execute(method);
    57. endTime = System.currentTimeMillis();
    58. int statusCode = response.getStatusLine().getStatusCode();
    59. logger.info("statusCode:" + statusCode);
    60. logger.info("调用API 花费时间(单位:毫秒):" + (endTime - startTime));
    61. if (statusCode != HttpStatus.SC_OK) {
    62. logger.error("Method failed:" + response.getStatusLine());
    63. status = 1;
    64. }
    65. // Read the response body
    66. body = EntityUtils.toString(response.getEntity());
    67. } catch (IOException e) {
    68. // 网络错误
    69. status = 3;
    70. } finally {
    71. logger.info("调用接口状态:" + status);
    72. }
    73. }
    74. return body;
    75. }
    76. public static void main(String[] args) {
    77. APIHttpClient ac = new APIHttpClient(apiURL);
    78. JsonArray arry = new JsonArray();
    79. JsonObject j = new JsonObject();
    80. j.addProperty("orderId", "中文");
    81. j.addProperty("createTimeOrder", "2015-08-11");
    82. arry.add(j);
    83. System.out.println(ac.post(arry.toString()));
    84. }
    85. /**
    86. * 0.成功 1.执行方法失败 2.协议错误 3.网络错误
    87. *
    88. * @return the status
    89. */
    90. public int getStatus() {
    91. return status;
    92. }
    93. /**
    94. * @param status
    95. *            the status to set
    96. */
    97. public void setStatus(int status) {
    98. this.status = status;
    99. }
    100. /**
    101. * @return the startTime
    102. */
    103. public long getStartTime() {
    104. return startTime;
    105. }
    106. /**
    107. * @return the endTime
    108. */
    109. public long getEndTime() {
    110. return endTime;
    111. }
    112. }

HttpClient通过Post方式发送Json数据的更多相关文章

  1. java 模拟http请求,通过流(stream)的方式,发送json数据和文件

    发送端: /** * 以流的方式 * 发送文件和json对象 * * @return */ public static String doPostFileStreamAndJsonObj(String ...

  2. HttPclient 以post方式发送json

    使用HttpClient 以POST的形式发送json字符串 步骤: 1.url .parameters 2.创建httpClient对象 3.创建HttpPost对象 4.为post对象设置参数 5 ...

  3. HttpClient发送Json数据到指定接口

    项目中遇到将Json数据发送到指定接口,于是结合网上利用HttpClient进行发送. /** * post发送json数据 * @param url * @param param * @return ...

  4. python 全栈开发,Day75(Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件)

    昨日内容回顾 基于对象的跨表查询 正向查询:关联属性在A表中,所以A对象找关联B表数据,正向查询 反向查询:关联属性在A表中,所以B对象找A对象,反向查询 一对多: 按字段:xx book ----- ...

  5. 使用Ajax方式POST JSON数据包(转)

    add by zhj: 用ajax发送json数据时注意两点, 第一,使用JSON.stringify()函数将data转为json格式的字符串,如下 data: JSON.stringify({   ...

  6. Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件

    一.Django与Ajax AJAX准备知识:JSON 什么是 JSON ? JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation) JSON 是轻 ...

  7. ajax 发送json数据时为什么需要设置contentType: "application/json”

    1. ajax发送json数据时设置contentType: "application/json”和不设置时到底有什么区别? contentType: "application/j ...

  8. ajax发送json数据时为什么需要设置contentType: "application/json”

    1. ajax发送json数据时设置contentType: "application/json”和不设置时到底有什么区别?contentType: "application/js ...

  9. 前端ajax用post方式提交json数据给后端时,网络报错 415

    项目框架:spring+springmvc+mybatis 问题描述:前端ajax用post方式提交json数据给后端时,网络报错 415 前端异常信息:Failed to load resource ...

随机推荐

  1. luogu1939 【模板】矩阵加速(数列)

    upd:现在推荐使用一个长度为 \(n\) 的一维向量.若状态矩阵 \(F\) 对下一时间的状态矩阵 \(F'\) 有影响,则 \(F'=FA\) 中的 转移矩阵 \(A\) 的赋值方法是: 若状态矩 ...

  2. java基础语法中容易出错的细节

    1 java中的数字默认类型为int **容易出现类型转换错误 long 定义的数字后面必须有 “l” “L” float 定义的数字后面必须有 “f” “F” java中比int表述范围大的数,不会 ...

  3. Linux中TTY是什么意思

    终端是一种字符型设备,它有多种类型,通常使用tty来简称各种类型的终端设备.tty是Teletype的缩写.Teletype是最早出现的一种终端 设备,很象电传打字机(或者说就是),是由Telety ...

  4. spring AOP详解二

    AOP实例(通过Proxy代理模式) Spring AOP使用纯java实现,不需要专门的编译过程和类装载器,它在运行期间通过代理方式向目标类织入增强代码,它更侧重于提供一种和Spring IoC容器 ...

  5. hdu图论题目分类

    =============================以下是最小生成树+并查集====================================== [HDU] 1213 How Many ...

  6. oracle查询包含大小写的数据

    查询包含小写的所有数据: select oper_no from info_oper where regexp_like(oper_no,'[[:lower:]]'); select oper_no  ...

  7. 关闭chrome浏览器的input香蕉黄背景

    chrome浏览器input的自动完成,点击之后自动输入,input的背景会变成香蕉黄,用如下方法修复: /* Change the white to any color ;) 就是给input设置内 ...

  8. python time模块 sys模块 collections模块 random模块 os模块 序列化 datetime模块

    一 collections模块 collections模块在内置的数据类型,比如:int.str.list.dict等基础之上额外提供了几种数据类型. 参考博客 http://www.pythoner ...

  9. Flask获取post提交数据

    完成示例 # flask 代码 from flask import Flask,request ... @app.route('/get_tasks',methods=["POST" ...

  10. d3 根据数据绘制svg

    , , , , ]; var circles = svg.selectAll("circle") .data(dataset) .enter() .append("cir ...