HttpClient通过Post方式发送Json数据
服务器用的是Springmvc,接口内容:
- @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访问的时候,代码如下:
- $.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"}]}, // Post 方式,data参数不能为空"",如果不传参数,也要写成"{}",否则contentType将不能附加在Request Headers中。
- 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方式访问,代码如下:
- 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;
- /**
- * 接口地址
- *
- * @param url
- */
- public APIHttpClient(String url) {
- if (url != null) {
- this.apiURL = url;
- }
- if (apiURL != null) {
- httpClient = new DefaultHttpClient();
- method = new HttpPost(apiURL);
- }
- }
- /**
- * 调用 API
- *
- * @param parameters
- * @return
- */
- public String post(String parameters) {
- String body = null;
- logger.info("parameters:" + parameters);
- if (method != null & parameters != null
- && !"".equals(parameters.trim())) {
- try {
- // 建立一个NameValuePair数组,用于存储欲传送的参数
- 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;
- }
- // Read the response body
- 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()));
- }
- /**
- * 0.成功 1.执行方法失败 2.协议错误 3.网络错误
- *
- * @return the status
- */
- public int getStatus() {
- return status;
- }
- /**
- * @param status
- * the status to set
- */
- public void setStatus(int status) {
- this.status = status;
- }
- /**
- * @return the startTime
- */
- public long getStartTime() {
- return startTime;
- }
- /**
- * @return the endTime
- */
- public long getEndTime() {
- return endTime;
- }
- }
HttpClient通过Post方式发送Json数据的更多相关文章
- java 模拟http请求,通过流(stream)的方式,发送json数据和文件
发送端: /** * 以流的方式 * 发送文件和json对象 * * @return */ public static String doPostFileStreamAndJsonObj(String ...
- HttPclient 以post方式发送json
使用HttpClient 以POST的形式发送json字符串 步骤: 1.url .parameters 2.创建httpClient对象 3.创建HttpPost对象 4.为post对象设置参数 5 ...
- HttpClient发送Json数据到指定接口
项目中遇到将Json数据发送到指定接口,于是结合网上利用HttpClient进行发送. /** * post发送json数据 * @param url * @param param * @return ...
- python 全栈开发,Day75(Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件)
昨日内容回顾 基于对象的跨表查询 正向查询:关联属性在A表中,所以A对象找关联B表数据,正向查询 反向查询:关联属性在A表中,所以B对象找A对象,反向查询 一对多: 按字段:xx book ----- ...
- 使用Ajax方式POST JSON数据包(转)
add by zhj: 用ajax发送json数据时注意两点, 第一,使用JSON.stringify()函数将data转为json格式的字符串,如下 data: JSON.stringify({ ...
- Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件
一.Django与Ajax AJAX准备知识:JSON 什么是 JSON ? JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation) JSON 是轻 ...
- ajax 发送json数据时为什么需要设置contentType: "application/json”
1. ajax发送json数据时设置contentType: "application/json”和不设置时到底有什么区别? contentType: "application/j ...
- ajax发送json数据时为什么需要设置contentType: "application/json”
1. ajax发送json数据时设置contentType: "application/json”和不设置时到底有什么区别?contentType: "application/js ...
- 前端ajax用post方式提交json数据给后端时,网络报错 415
项目框架:spring+springmvc+mybatis 问题描述:前端ajax用post方式提交json数据给后端时,网络报错 415 前端异常信息:Failed to load resource ...
随机推荐
- Jayrock.Json读取json数据(net)
1 : 首 先 下 载 Jayrock.Json.dll 文 件 , 放 入 bin 目 录 中 : 地 址 : http://www.filediag.com/down/Jayrock.Json.d ...
- rocketmq源码分析4-事务消息实现原理
为什么消息要具备事务能力 参见还是比较清晰的.简单的说 就是在你业务逻辑过程中,需要发送一条消息给订阅消息的人,但是期望是 此逻辑过程完全成功完成之后才能使订阅者收到消息.业务逻辑过程 假设是这样的: ...
- python面向对象、模块讲解
(1)模块的介绍: 1.什么是模块 模块是一系列功能的集合体 常见的模块形式(自定义模块.第三方模块.内置模块): 1.一个module.py文件就是一个模块,文件名是module.py,而模 ...
- c/c++内存泄露的检测方法
此文内容摘自 https://zhuanlan.zhihu.com/p/22664202 作为 从零开始的 JSON 库教程(三):解析字符串解答篇 的笔记 1A. Windows 下的内存泄漏 ...
- 算法golang篇
1.slice反转,偏移 func reverse(s []int) { , len(s) - ; i < j; i, j = i+, j- { s[i], s[j] = s[j], s[i] ...
- Welcome-to-Swift-23访问控制(Access Control)
访问控制可以限定你在源文件或模块中访问代码的级别,也就是说可以控制哪些代码你可以访问,哪些代码你不能访问.这个特性可以让我们隐藏功能实现的一些细节,并且可以明确的指定我们提供给其他人的接口中哪些部分是 ...
- Synergy 使用方法备忘
Synergy 是 Symless 公司推出的「鼠标键盘共享软件」(mouse and keyboard sharing software),其功能还包括「共享剪贴板」(sharing clipboa ...
- Django notes I: collection of links to the Django document
Links to the Django documents: the Django template language automatically generated context variable ...
- docker (centOS 7) 使用笔记3 - 修改docker默认的虚拟网址
近日在使用VPN时发现和docker的虚拟网址发生了冲突,都是172.17.0.1,故需要修改docker的默认网址. 1. 当前状态 # ifconfig docker0: flags=<UP ...
- python logger日志工具类
pytest命令行执行默认不会打印log信息,需要加‘-s’参数或者 ‘–capture=no’,即pytest -s #! /usr/bin/env python # coding=gbk impo ...