分享

SpringMVC实战(五)

 翼ZYDREAM 2018-09-16

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

2016年07月26日 10:52:53 Ricky_Fung 阅读数:17971 标签: springmvcpostjson 更多
个人分类: Spring MVC
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/FX_SKY/article/details/52033671

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();
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96

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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

资源下载

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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约