美文网首页
SpringMvc @RequetsBody报415错误

SpringMvc @RequetsBody报415错误

作者: 小小程序猿s | 来源:发表于2019-02-14 14:14 被阅读0次

整合步骤
1、需要jar
jackson-annotations,jackson-databind,jackson-core,
2、开启mvc自动扫描注解
<mvc:annotation-driven />
会自动扫描到jar中的解析器并注册到容器中
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJackson2HttpMessageConverter" />
</list>
</property>
</bean>
<bean id="mappingJackson2HttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>text/json;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
3、客户端的Content-Type 必须为application/json

服务端demo
@RequestMapping(value = "/push",method = RequestMethod.POST)
public void receiveAll(HttpServletRequest req, HttpServletResponse res,@RequestBody ReceiveModel obj){
ServletUtils.toJson(req,res);
}

客户端demo

1、封装请求
public static String postJsonBody(String url, Map<String, Object> paramsMap) {
String result = null;
CloseableHttpClient httpClient = getHttpClient();

    try {
        HttpPost httppost = new HttpPost(url);
        httppost.addHeader("charset", "UTF-8");
        httppost.addHeader("Content-Type", "application/json");

        String body = JsonUtils.writeValue(paramsMap);
        httppost.setEntity(new StringEntity(body, Charset.forName("UTF-8")));

        HttpResponse response = httpClient.execute(httppost);
        result = getPostResult(response);
        httpClient.close();
    } catch (Exception e) {
        log.error("post " + url + " exception", e);
    }

    return result;
}

2、请求发送
Map<String,Object> map = new HashMap<>();
map.put("companyName","公司简称");
map.put("pushTime","2018-11-29 16:39:23");
map.put("signContent","sign");
List<Map> list = new ArrayList<>();
for(int k=1;k<10;k++){
Map<String,Object> map2 = new HashMap<>();
map2.put("telPhone","1841005570"+k);
map2.put("scenario","营销剧本XX");
list.add(map2);
}
map.put("content",list);
System.out.println(JsonUtils.writeValue(map));
String post = HttpUtils.postBody("url地址", JsonUtils.writeValue(map));
System.out.println(post);

相关文章

网友评论

      本文标题:SpringMvc @RequetsBody报415错误

      本文链接:https://www.haomeiwen.com/subject/kcdeeqtx.html