zoukankan      html  css  js  c++  java
  • SpringMVC接收Post的实体/JSon数据

    接口代码:

    @ResponseBody
    @RequestMapping(value = "/test",method = RequestMethod.POST)/*只允许POST方式调用此接口*/
    public returnType functionName(/*POST数据内容*/@RequestBody parameterType parameterName,HttpServletRequest request) throws Exception {}

    配置:

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    </bean>

    依赖文件:

    <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
    </dependency>
    <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.2.1</version>
    </dependency>

    逻辑代码:

    /*如果是List数据  在接收到数据之后  需要转换类型*/

    /*否则不需要转换*/

    ObjectMapper mapper = new ObjectMapper();

    for (int i = 0; i < behaviorList.size(); i++) {
    /*由于客户端POST过来的List是LinkedHashMap类型的数据
    * 所以需要用ObjectMapper进行解析转换*/

    ClassName clazz = mapper.convertValue(List.get(i),ClassName.class);

    }

    实体类:

    如果访问端是C#   DateTime类型要重置为String类型,否则服务端无法解析

    访问端(C#):

    /*POST之前  要先将实体类转换为JSon字符串   然后再转换成Byte数组*/

     HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(uri);

    httpReq.Method = "POST";
    httpReq.Accept = "*/*";
    httpReq.ContentType = "application/json; charset=utf-8";

    byte[] buffer = Encoding.UTF8.GetBytes(dataJsonString);

    httpReq.ContentLength = buffer.Length;
    httpReq.GetRequestStream().Write(buffer, 0, buffer.Length);

    HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
    Stream respStream = httpResp.GetResponseStream();
    StreamReader respStreamReader = new StreamReader(respStream, Encoding.UTF8);
    string result = respStreamReader.ReadToEnd();

    以上是个人遇到问题时候     尝试了一天时间找到的解决办法    

    本人java菜鸟   解决方案也许比较片面或老旧或笨拙    望大神指教 

    也希望能够帮到遇到同样问题的朋友

  • 相关阅读:
    yarn 集群任务全部pending 事件记录
    flink 在使用upsert_kafka connector 时报错,找不到类Exeption: Could not find any factory for identifier 'upsert-kafka' that implements 'org.apache.flink.table.factories.DynamicTableFactory' in the classpath.
    SpringBoot 项目无法启动,且无任何日志
    Python之PyQt编程
    转:redis 节约内存之Instagram的Redis实践
    云计算 私有云 公有云 混合云
    java 类继承估计99%的人都不知道的问题?
    Java Vector 类
    Java LinkedList 类
    Java Queue 接口
  • 原文地址:https://www.cnblogs.com/JosephBee/p/5670571.html
Copyright © 2011-2022 走看看