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;  
    }  
}  

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值