springboot报406

我将消息队列消费者和主项目分开,并且使用RestOperations来调用action,结果却返回406,

	public Map postForOperation(String path, Map params) throws IOException {
		String url = serverAddress + path;
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("text/json; charset=UTF-8");
		headers.setContentType(type);
		headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
		url += StringUtils.MapToPathParam(params);
		logger.info(url);
		HttpEntity formEntity = new HttpEntity<>(null, headers);
		Map object = restOperations.postForObject(url, formEntity, Map.class);
		System.out.println(object);
		return object;
	}

仔细debug发现action层被成功调用了,代码也执行了,也没有抛出异常,在网上一查是返回的格式转化失败的问题。于是我改了好半天的MediaType,但是怎么都不行,后来查到资料发现可能和我使用了WebMvcConfigurerAdapter有关系。之前为了将返回的字符串null转化为空字符串(都是为了移动端)而使用了这个转化工具,而这个工具需要设置supportedMediaTypes

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter{
    @Override
    public void configureMessageConverters(List> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        converter.setFeatures(SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteNullBooleanAsFalse);
        List mediaTypes = new ArrayList<>();
        mediaTypes.add(MediaType.parseMediaType("text/plain;charset=utf-8"));
        mediaTypes.add(MediaType.parseMediaType("text/html;charset=utf-8"));
        mediaTypes.add(MediaType.parseMediaType("text/json;charset=utf-8"));
        mediaTypes.add(MediaType.parseMediaType("application/json;charset=utf-8"));
        converter.setSupportedMediaTypes(mediaTypes);
        converters.add(converter);
   }
}

加上supportedMediaTypes后就正常了。

你可能感兴趣的:(bug)