1、导入所需jar
jackson-annotations,jackson-databind,jackson-core。
2、开启mvc自动扫描注册映射器
<mvc:annotation-driven />
<!--配置全局拦截器-->
<mvc:interceptors>
<bean class="com.zqf.marketing.aspect.ControllerInterceptor"></bean>
</mvc:interceptors>
<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
4、示例整合
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);
说明:关于出现自定义拦截器失效问题,可参考以下链接
使用自定义Interceptor和mvc:annotation-driven配置自定义拦截器失效问题