HttpClient通过Post方式发送Json数据

来源:互联网 发布:2年java开发工程师简历 编辑:程序博客网 时间:2024/05/22 03:45
服务器用的是Springmvc,接口内容:

[java] view plain copy
 print?
  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访问的时候,代码如下:

[javascript] view plain copy
 print?
  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方式访问,代码如下:


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