1. 程式人生 > >HttpClient通過Post方式發送Json數據

HttpClient通過Post方式發送Json數據

傳參數 alert pat gets oar source 內容 {} 訂單

轉載:http://blog.csdn.net/majian_1987/article/details/47728769

服務器用的是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. 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數據