生活随笔
收集整理的這篇文章主要介紹了
HttpClient通过Post方式发送Json数据
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
服務器用的是Springmvc,接口內容:
?
[java]?view plaincopy print?
@ResponseBody??@RequestMapping(value="/order",method=RequestMethod.POST)??public?boolean?order(HttpServletRequest?request,@RequestBody?List<Order>?orders)?throws?Exception?{??????AdmPost?admPost?=?SessionUtil.getCurrentAdmPost(request);??????if(admPost?==?null){??????????throw?new?RuntimeException("[OrderController-saveOrUpdate()]?當前登陸的用戶職務信息不能為空!");??????}??????try?{??????????this.orderService.saveOrderList(orders,admPost);??????????Loggers.log("訂單管理",admPost.getId(),"導入",new?Date(),"導入訂單成功,訂單信息-->?"?+?GsonUtil.toString(orders,?new?TypeToken<List<Order>>()?{}.getType()));??????????return?true;??????}?catch?(Exception?e)?{??????????e.printStackTrace();??????????Loggers.log("訂單管理",admPost.getId(),"導入",new?Date(),"導入訂單失敗,訂單信息-->?"?+?GsonUtil.toString(orders,?new?TypeToken<List<Order>>()?{}.getType()));??????????return?false;??????}??}??
通過ajax訪問的時候,代碼如下:
?
?
[javascript]?view plaincopy print?
??????????????????$.ajax({??????type?:?"POST",??????contentType?:?"application/json;?charset=utf-8",??????url?:?ctx?+?"order/saveOrUpdate",??????dataType?:?"json",??????anysc?:?false,??????data?:?{orders:[{orderId:"11",createTimeOrder:"2015-08-11"}]},??????success?:?function(data){??????????if?(data?!=?undefined?&&?$.parseJSON(data)?==?true){??????????????$.messager.show({??????????????????title:'提示信息',??????????????????msg:'保存成功!',??????????????????timeout:5000,??????????????????showType:'slide'??????????????});??????????}else{??????????????$.messager.alert('提示信息','保存失敗!','error');??????????}??????},??????error?:?function(XMLHttpRequest,?textStatus,?errorThrown)?{??????????alert(errorThrown?+?':'?+?textStatus);?????}??});??
通過HttpClient方式訪問,代碼如下:
?
?
?
[java]?view plaincopy print?
package?com.ec.spring.test;????import?java.io.IOException;??import?java.nio.charset.Charset;????import?org.apache.commons.logging.Log;??import?org.apache.commons.logging.LogFactory;??import?org.apache.http.HttpResponse;??import?org.apache.http.HttpStatus;??import?org.apache.http.client.HttpClient;??import?org.apache.http.client.methods.HttpPost;??import?org.apache.http.entity.StringEntity;??import?org.apache.http.impl.client.DefaultHttpClient;??import?org.apache.http.util.EntityUtils;????import?com.google.gson.JsonArray;??import?com.google.gson.JsonObject;????public?class?APIHttpClient?{????????????private?static?String?apiURL?=?"http://192.168.3.67:8080/lkgst_manager/order/order";??????private?Log?logger?=?LogFactory.getLog(this.getClass());??????private?static?final?String?pattern?=?"yyyy-MM-dd?HH:mm:ss:SSS";??????private?HttpClient?httpClient?=?null;??????private?HttpPost?method?=?null;??????private?long?startTime?=?0L;??????private?long?endTime?=?0L;??????private?int?status?=?0;????????????public?APIHttpClient(String?url)?{????????????if?(url?!=?null)?{??????????????this.apiURL?=?url;??????????}??????????if?(apiURL?!=?null)?{??????????????httpClient?=?new?DefaultHttpClient();??????????????method?=?new?HttpPost(apiURL);????????????}??????}????????????public?String?post(String?parameters)?{??????????String?body?=?null;??????????logger.info("parameters:"?+?parameters);????????????if?(method?!=?null?&?parameters?!=?null??????????????????&&?!"".equals(parameters.trim()))?{??????????????try?{????????????????????????????????????method.addHeader("Content-type","application/json;?charset=utf-8");??????????????????method.setHeader("Accept",?"application/json");??????????????????method.setEntity(new?StringEntity(parameters,?Charset.forName("UTF-8")));??????????????????startTime?=?System.currentTimeMillis();????????????????????HttpResponse?response?=?httpClient.execute(method);????????????????????????????????????endTime?=?System.currentTimeMillis();??????????????????int?statusCode?=?response.getStatusLine().getStatusCode();????????????????????????????????????logger.info("statusCode:"?+?statusCode);??????????????????logger.info("調用API?花費時間(單位:毫秒):"?+?(endTime?-?startTime));??????????????????if?(statusCode?!=?HttpStatus.SC_OK)?{??????????????????????logger.error("Method?failed:"?+?response.getStatusLine());??????????????????????status?=?1;??????????????????}????????????????????????????????????body?=?EntityUtils.toString(response.getEntity());????????????????}?catch?(IOException?e)?{??????????????????????????????????status?=?3;??????????????}?finally?{??????????????????logger.info("調用接口狀態:"?+?status);??????????????}????????????}??????????return?body;??????}????????public?static?void?main(String[]?args)?{??????????APIHttpClient?ac?=?new?APIHttpClient(apiURL);??????????JsonArray?arry?=?new?JsonArray();??????????JsonObject?j?=?new?JsonObject();??????????j.addProperty("orderId",?"中文");??????????j.addProperty("createTimeOrder",?"2015-08-11");??????????arry.add(j);??????????System.out.println(ac.post(arry.toString()));??????}????????????public?int?getStatus()?{??????????return?status;??????}????????????public?void?setStatus(int?status)?{??????????this.status?=?status;??????}????????????public?long?getStartTime()?{??????????return?startTime;??????}????????????public?long?getEndTime()?{??????????return?endTime;??????}??} ?
轉載于:https://www.cnblogs.com/ceshi2016/p/7481408.html
總結
以上是生活随笔為你收集整理的HttpClient通过Post方式发送Json数据的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。