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

你可能感兴趣的:(Spring,MVC)