HttpClient通過Post方式發送Json數據

服務器用的是Springmvc,接口內容:

?

[java]?view plaincopy
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 plaincopy
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 plaincopy
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. } ?

轉載于:https://www.cnblogs.com/ceshi2016/p/7481408.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/454765.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/454765.shtml
英文地址,請注明出處:http://en.pswp.cn/news/454765.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

openssl、ssh

PKI&#xff1a;公鑰基礎設施&#xff0c;保證服務器向客戶端發送的證書的可靠性&#xff1b;簽證機構&#xff1a;CA注冊機構&#xff1a;RA證書吊銷列表&#xff1a;CRL證書存取庫&#xff1a;CAB威瑞信——verisignGlobalSign賽門鐵克AsiaCOM國際標準化組織定義了證書的標準…

php圖型分析插件,IMAGE縮略圖插件

應用信息 名稱: IMAGE縮略圖插件 售價: (免費) 應用ID: IMAGE 最低要求: Z-BlogPHP 1.5.1 Zero Build 151740版 本: 2 發布日期: 2014-08-27PHP最低版本要求: 5.3 更新日期: 2018-05-21立即購買 加入購物車作者信息 開發者ID: 十五樓的鳥兒 本站用戶組: 管理員 聯系郵箱: adm…

職業生涯步步高

在擔任公司高管的幾年間&#xff0c;我面試過數以百計的各個層面的員工&#xff0c;其中最讓我感到遺憾的一個現象就是很多人有著非常好的素質&#xff0c;甚至有的還是名校的畢業生&#xff0c;因為不懂得去規劃自己的職業&#xff0c;在工作多年后&#xff0c;依然拿著微薄的…

httpd2.2配置文件詳解

一丶Apache常用目錄詳解1) /etc/httpd/conf/httpd.confhttpd.conf是Apache的主配文件&#xff0c;整個Apache也不過就是這個配置文件&#xff0c;里面幾乎包含了所有的配置。有的distribution都將這個文件拆分成數個小文件分別管理不同的參數。但是主要配置文件還是以這個文件為…

2017.9.5 postgresql加密函數的使用

需要安裝的插件的名字&#xff1a;pgcrypto官網地址&#xff1a;https://www.postgresql.org/docs/9.4/static/pgcrypto.htmlstackoverflow:https://stackoverflow.com/questions/8000740/how-do-i-install-pgcrypto-in-postgresql-9-1-on-windows/46046367#46046367https://st…

php 序列化方法,PHP序列化操作方法分析

本文實例講述了PHP序列化操作方法。分享給大家供大家參考&#xff0c;具體如下&#xff1a;序列化就是將變量數據轉換為字符串(跟類型轉換機制不同)&#xff0c;一般應用于存儲數據(文件)&#xff0c;然后在別的情形下恢復(反序列化)序列化&#xff1a;$val serialize($var);f…

Redis入門到精通-Redis數據類型

2019獨角獸企業重金招聘Python工程師標準>>> 登錄Redis數據庫 [rootlocalhost bin]# /usr/local/redis/bin/redis-cli String類型 ? String 數據結構是簡單的key-value類型&#xff0c;value其實不僅是String&#xff0c;也可以是數字&#xff0c;是包含很多種類型…

裝機之 BIOS、EFI與UEFI詳解

在我們的電腦中&#xff0c;都有一塊黑色的小芯片。但是請千萬不要小看它&#xff0c;如果它損壞或者數據錯誤亂套的話&#xff0c;恭喜&#xff0c;如果不會“救回”這個小芯片&#xff0c;那么這臺電腦可以掛閑魚賣零件了…… 這個小芯片是什么呢&#xff1f;對&#xff0c;…

c/c++筆試題

微軟亞洲技術中心的面試題&#xff01;&#xff01;&#xff01; 1&#xff0e;進程和線程的差別。 線程是指進程內的一個執行單元,也是進程內的可調度實體. 與進程的區別: (1)調度&#xff1a;線程作為調度和分配的基本單位&#xff0c;進程作為擁有資源的基本單位 (2)并發性&…

php 模板 php + mysql + myodbc,連接MySQL數據庫在ASP中,就用MyODBC

我們大家都知道ASP與MySQL連接現在應用最為廣泛的兩種辦法是&#xff0c;一是使用組件&#xff0c;經常使用的是MySQL(和PHP搭配之最佳組合)X&#xff0c;可惜價格很貴。另一個就是用MyODBC來連接MySQL數據庫&#xff0c;下面我們就來看看第二種方式。 試驗的平臺&#xff1a; …

Android Gradle和Gradle插件區別

2019獨角獸企業重金招聘Python工程師標準>>> 一、引言 1、什么是Gradle?什么是Gradle插件? build.gradle中依賴的classpath com.android.tools.build:gradle:2.1.2和gradle-wrapper.properties中的distributionUrlhttps\://services.gradle.org/distributions/gra…

裝機之MBR和GPT

MBR分區 MBR的意思是“主引導記錄”&#xff0c;是IBM公司早年間提出的。它是存在于磁盤驅動器開始部分的一個特殊的啟動扇區。這個扇區包含了已安裝的操作系統系統信息&#xff0c;并用一小段代碼來啟動系統。如果你安裝了Windows&#xff0c;其啟動信息就放在這一段代碼中—…

Linux 文件打亂順序

cat in.txt | awk BEGIN{srand()}{print rand()"\t"$0} | sort -k1,1 -n | cut -f2- > out.txt sort -R in.txt > out.txt 后者要計算每行的hash&#xff0c;再排序&#xff0c;在文件內容比較多的情況下前者要比后者快得多 參考文獻&#xff1a; http://blog.…

php 計算 目錄大小,php計算整個目錄大小的方法

本文實例講述了php計算整個目錄大小的方法。分享給大家供大家參考。具體實現方法如下&#xff1a;/*** Calculate the full size of a directory** author Jonas John* version 0.2* link http://www.jonasjohn.de/snippets/php/dir-size.htm* param string $DirectoryPath Dir…

實驗報告3

中國人民公安大學 Chinese people’ public security university 網絡對抗技術 實驗報告 實驗三 密碼破解技術 學生姓名 陸圣宇 年級 2014 區隊 三 指導教師 高見 信息技術與網絡安全學院 2016年11月7日 實驗任務總綱 2016—2017 學年 第 一 學期 一、實驗目的 1&am…

裝機之windows10和ubuntu雙系統

制作系統U盤 下載Ubuntu16.04 我們首先去Ubuntu的官網下載一個Ubuntu16.04的iso鏡像文件。當然里面也有優麒麟&#xff0c;其實就是把Ubuntu16.04漢化了一下&#xff0c;個人推薦安裝Ubuntu16.04 體驗上可能好一些。 利用軟碟通制作 不會的可以查看此教程https://blog.csdn…

函數之內置函數1

什么是內置函數&#xff1a;別人已經定義好了的函數&#xff0c;我們只管拿來調用就好 locals&#xff1a;局部作用域中的變量 globals&#xff1a;全局作用域中的變量 這兩者在全局執行&#xff0c;結果一樣&#xff1b;在局部中locals表示函數內的名字&#xff0c;返回的是一…

matlab var std,Matlab var std cov 函數解析

在Matlab中使用var求樣本方差&#xff0c;使用std求標準差&#xff01;首先來了解一下方差公式&#xff1a;p [-0.92 0.73 -0.47 0.74 0.29; -0.08 0.86 -0.67 -0.52 0.93]p -0.9200 0.7300 -0.4700 0.7400 0.2900-0.0800 0.8600 -0.6700 -0.5200 0.9300…

Java中什么是匿名對象,空參構造方法輸出創建了幾個匿名對象,屬性聲明成static...

package com.swift; //使用無參構造方法自動生成對象&#xff0c;序號不斷自增 public class Person {private static int count; //如果在定義類時&#xff0c;使用的是靜態的屬性&#xff0c;則得到的結果是不同的。count生命周期長&#xff0c;與類相同public int id;public…

裝機之制作系統U盤

工具&#xff1a;UltraISO&#xff08;軟碟通&#xff09;&#xff0c;iso鏡像 在制作系統U盤的時候我們需要去下一個軟件——UltraISO&#xff08;軟碟通&#xff09;&#xff0c;這個自己去百度搜索一下應該就能出來的。下載安裝完以后&#xff0c;我們打開軟碟通的界面打開…