SpringMVC实战(五)-处理POST提交JSON数据

1.表单提交

2.JSON串

1、客户端请求

        String url = "http://localhost:8080/order/create";
        String data = "{\"id\":3, \"category\":\"IT数码\"}";
        try {
            String result = HttpUtils.post(url, data);
            System.out.println("result:"+result);
        } catch (Exception e) {
            e.printStackTrace();
        }

HttpUtils.java

package com.yirendai.rulebase.node.util;


import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * ${DESCRIPTION}
 *
 * @author Ricky Fung
 * @create 2016-06-24 13:11
 */
public final class HttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    public static final int CONNECTION_TIMEOUT = 60*1000;

    public static final int SOCKET_TIMEOUT = 60*1000;

    public static final String USER_AGENT_HEADER = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36";
    public static final String ACCEPT_HEADER = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
    public static final String ACCEPT_LANGUAGE_HEADER = "zh-CN,zh;q=0.8,en;q=0.6";

    private static final  CloseableHttpClient httpclient = HttpClientManager.getHttpClient();;

    public static String post(String url, String data) throws IOException {

        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("User-Agent", USER_AGENT_HEADER);
        httpPost.setHeader("Accept", ACCEPT_HEADER);
        httpPost.setHeader("Accept-Language", ACCEPT_LANGUAGE_HEADER);

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(CONNECTION_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT).build();

        httpPost.setConfig(requestConfig);

        CloseableHttpResponse response = null;
        try {

            StringEntity stringEntity = new StringEntity(data, "UTF-8");
            stringEntity.setContentType("text/json");

            httpPost.setEntity(stringEntity);
            httpPost.setHeader("Content-type", "application/json");

            response = httpclient.execute(httpPost);

            int code = response.getStatusLine().getStatusCode();

            if (code == HttpStatus.SC_OK) {

                HttpEntity entity = response.getEntity();
                if(entity!=null){
                    // Gzip
                    if (entity.getContentEncoding()!=null && "GZIP".equalsIgnoreCase(entity
                            .getContentEncoding().getName())) {
                        entity = new GzipDecompressingEntity(entity);
                    }

                    try{
                        return EntityUtils.toString(entity);
                    }finally{
                        EntityUtils.consume(entity);
                    }
                }
            } else {
                logger.error("server:{} response error, statusCode:{}", url, code);
            }

        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("post error", e);
                }
            }
        }
        return null;
    }
}
2、SpringMVC Controller处理
package com.ricky.codelab.springmvc.controller;

import com.alibaba.fastjson.JSON;
import com.ricky.codelab.springmvc.domain.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.atomic.AtomicLong;

/**
 * ${DESCRIPTION}
 *
 * @author Ricky Fung
 * @create 2016-07-26 10:08
 */
@Controller
@RequestMapping("/order")
public class OrderController {

    private AtomicLong counter = new AtomicLong(1);

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Oder create(@RequestBody String data){

        System.out.println("data:"+data);

        Order order = JSON.parseObject(data, Oder.class);
        order.setId(counter.getAndIncrement());

        return order;
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Oder create(@RequestBody Order oder){

        System.out.println("order:"+ oder);
        oder.setId(counter.getAndIncrement());

        return oder;
    }
}

资源下载

https://github.com/ByteAce/springmvc4-samples

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值