@Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { /*FastJsonHttpMessageConverter4 converter = new FastJsonHttpMessageConverter4(); FastJsonConfig config = new FastJsonConfig(); config.setSerializerFeatures(SerializerFeature.WriteMapNullValue,//保留空的字段 SerializerFeature.WriteNullStringAsEmpty,//String null -> "" SerializerFeature.WriteNullNumberAsZero);//Number null -> 0 converter.setFastJsonConfig(config); converter.setDefaultCharset(Charset.forName("UTF-8"));*/ MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter(); List<MediaType> mediaTypes = new ArrayList<>(); mediaTypes.add(MediaType.APPLICATION_JSON_UTF8); mediaTypes.add(MediaType.TEXT_HTML); jacksonConverter.setSupportedMediaTypes(mediaTypes); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); jacksonConverter.setObjectMapper(objectMapper); converters.add(jacksonConverter); //converters.add(responseBodyConverter()); }
protected RestTemplate getRestTemplate() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.registerModule(new Jackson2HalModule()); MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON)); converter.setObjectMapper(mapper); return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter)); }
@Test public void testZg2Template() { Zg2proRestTemplate z0 = new Zg2proRestTemplate(); assertThat(z0.getErrorHandler()).isInstanceOf(RestTemplateErrorHandler.class); assertThat(z0.getInterceptors().size()).isGreaterThan(0); List<ClientHttpRequestInterceptor> lInterceptors = new ArrayList<>(); lInterceptors.add(new LoggingRequestInterceptor()); List<HttpMessageConverter<?>> covs = z0.getMessageConverters(); z0 = new Zg2proRestTemplate(null, lInterceptors); assertThat(z0).isNotNull(); Zg2proRestTemplate z = new Zg2proRestTemplate(covs, null); z.setInterceptors(lInterceptors); assertThat(z.getInterceptors().size()).isGreaterThan(0); z.setRequestFactory(LoggingRequestFactoryFactory.build()); assertThat(z.getInterceptors().size()).isGreaterThan(0); assertThat(z.getErrorHandler()).isInstanceOf(RestTemplateErrorHandler.class); rt.getRestTemplate().setRequestFactory(z.getRequestFactory()); ResponseEntity<String> resp; resp = rt.getForEntity(MockedControllers.TEST_URL_GET_BLANK_REPLY, String.class); assertNotNull(resp); ReturnedStructure rs = rt.getForObject(TEST_URL_GET_STRUCTURE, ReturnedStructure.class); assertThat(rs.getFieldOne()).isEqualTo(12); }
@Test public void postsEndWithPathParam() { String result = restTemplate.postForObject( controllerUrl + "sayhello/{name}", null, String.class, "world"); assertThat(jsonOf(result, String.class), is("hello world")); List<HttpMessageConverter<?>> convertersOld = restTemplate.getMessageConverters(); List<HttpMessageConverter<?>> converters = new ArrayList<>(); converters.add(new MappingJackson2HttpMessageConverter()); restTemplate.setMessageConverters(converters); result = restTemplate.postForObject( controllerUrl + "sayhello/{name}", null, String.class, "中 国"); assertThat(result, is("hello 中 国")); restTemplate.setMessageConverters(convertersOld); }
/** * 修改自定义消息转换器 * @param converters 消息转换器列表 */ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { //调用父类的配置 super.configureMessageConverters(converters); //创建fastJson消息转换器 FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); //处理中文乱码问题 List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); fastConverter.setSupportedMediaTypes(fastMediaTypes); //创建配置类 FastJsonConfig fastJsonConfig = new FastJsonConfig(); //修改配置返回内容的过滤 fastJsonConfig.setSerializerFeatures( SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty ); fastConverter.setFastJsonConfig(fastJsonConfig); //将fastjson添加到视图消息转换器列表内 converters.add(fastConverter); }
@SuppressWarnings("unchecked") private void writePart(String name, HttpEntity<?> partEntity, OutputStream os) throws IOException { Object partBody = partEntity.getBody(); Class<?> partType = partBody.getClass(); HttpHeaders partHeaders = partEntity.getHeaders(); MediaType partContentType = partHeaders.getContentType(); for (HttpMessageConverter<?> messageConverter : this.partConverters) { if (messageConverter.canWrite(partType, partContentType)) { HttpOutputMessage multipartMessage = new MultipartMixedConverter.MultipartHttpOutputMessage(os); multipartMessage.getHeaders().setContentDispositionFormData(name, null); if (!partHeaders.isEmpty()) { multipartMessage.getHeaders().putAll(partHeaders); } ((HttpMessageConverter<Object>) messageConverter).write(partBody, partContentType, multipartMessage); return; } } throw new HttpMessageNotWritableException( "Could not write request: no suitable HttpMessageConverter found for request type [" + partType.getName() + "]"); }
/** * 是否有必要模仿Spring不提供RestTemplate,只提供RestTemplateBuilder * * @return dummy */ @Bean(name = WxBeans.WX_API_TEMPLATE_NAME) public WxApiTemplate wxApiTemplate() { RestTemplateBuilder builder = new RestTemplateBuilder(); builder = builder.requestFactory(new WxApiHttpRequestFactory(wxProperties)) .errorHandler(new WxResponseErrorHandler()); HttpMessageConverters converters = this.messageConverters.getIfUnique(); List<HttpMessageConverter<?>> converterList = new ArrayList<>(); // 加入默认转换 converterList.add(new WxHttpInputMessageConverter()); if (converters != null) { converterList.addAll(converters.getConverters()); builder = builder.messageConverters(Collections.unmodifiableList(converterList)); } return new WxApiTemplate(builder.build()); }
@Override public BizRes beforeBodyWrite(BizRes body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { String deviceToken = response.getHeaders().getFirst(requestHeaderProperties.getDeviceToken()); if (body instanceof ErrorRes) { ((ErrorRes) body).setVd(deviceToken); return body; } if (body instanceof SuccessRes) { ((SuccessRes) body).setVd(deviceToken); return body; } SuccessRes res = new SuccessRes(body); res.setVd(deviceToken); return res; }
protected AbstractZg2proRestTemplate(SimpleModule sm) { super(); //converters List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); messageConverters.add(new FormHttpMessageConverter()); messageConverters.add(new StringHttpMessageConverter()); messageConverters.add(new ByteArrayHttpMessageConverter()); messageConverters.add(new ResourceHttpMessageConverter()); ObjectMapper jsonMapper = camelToKebabObjectMapper(sm); messageConverters.add(new MappingJackson2HttpMessageConverter(jsonMapper)); this.setMessageConverters(messageConverters); //errors handling setErrorHandler(new RestTemplateErrorHandler()); /* //interceptors LoggingRequestInterceptor lri = new LoggingRequestInterceptor(); this.setInterceptors(new ArrayList<>()); this.getInterceptors().add(lri); this.setRequestFactory(LoggingRequestFactoryFactory.build(lri)); */ }
public RestTemplate validateRestTemplate(RestTemplate restTemplate) { boolean containsMappingJackson2HttpMessageConverter = false; for (HttpMessageConverter<?> converter : restTemplate.getMessageConverters()) { if (converter instanceof MappingJackson2HttpMessageConverter) { containsMappingJackson2HttpMessageConverter = true; } } if (!containsMappingJackson2HttpMessageConverter) { throw new IllegalArgumentException( "The RestTemplate does not contain a required " + "MappingJackson2HttpMessageConverter."); } return restTemplate; }
TwitterEscapingFormHttpMessageConverter() { setCharset(Charset.forName("UTF-8")); List<HttpMessageConverter<?>> partConverters = new ArrayList<>(); partConverters.add(new ByteArrayHttpMessageConverter()); StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter( Charset.forName("UTF-8")); stringHttpMessageConverter.setWriteAcceptCharset(false); partConverters.add(stringHttpMessageConverter); partConverters.add(new ResourceHttpMessageConverter()); setPartConverters(partConverters); }
@Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { MappingJackson2HttpMessageConverter jackson2HttpMessageConverter=new MappingJackson2HttpMessageConverter(); ObjectMapper mapper=jackson2HttpMessageConverter.getObjectMapper(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); mapper.setDateFormat(sdf); // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); //允许key没有使用双引号的json mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); //注册枚举反序列化时候忽略大小写 mapper.registerModule(JsonUtil.getEnumSimpleModule()); converters.add(jackson2HttpMessageConverter); super.configureMessageConverters(converters); }
@Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); builder.indentOutput(true).dateFormat(new SimpleDateFormat("yyyy-MM-dd")); converters.add(new MappingJackson2HttpMessageConverter(builder.build())); converters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build())); }
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { MappingFastJsonValue container = getOrCreateContainer(body); beforeBodyWriteInternal(container, selectedContentType, returnType, request, response); return container; }
@Autowired protected void setConverters(HttpMessageConverter<?>[] converters) { this.mappingJackson2HttpMessageConverter = Arrays.asList(converters).stream().filter( hmc -> hmc instanceof MappingJackson2HttpMessageConverter).findAny().get(); Assert.assertNotNull( "the JSON message converter must not be null", this.mappingJackson2HttpMessageConverter); }
@Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { final ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter(); final List<MediaType> list = new ArrayList<>(); list.add(MediaType.IMAGE_JPEG); list.add(MediaType.APPLICATION_OCTET_STREAM); arrayHttpMessageConverter.setSupportedMediaTypes(list); converters.add(arrayHttpMessageConverter); super.configureMessageConverters(converters); }
/** * 配置使用springmvc fastjson * @return */ @Bean public HttpMessageConverters fastJsonHttpMessageConverters() { FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); fastConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<?> converter = fastConverter; return new HttpMessageConverters(converter); }
/** * 配置fastJson * @param converters */ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); fastConverter.setFastJsonConfig(fastJsonConfig); converters.add(fastConverter); super.configureMessageConverters(converters); }
@Override public void encode(Object requestBody, Type bodyType, RequestTemplate request) throws EncodeException { if (requestBody != null) { Class<?> requestType = requestBody.getClass(); Collection<String> contentTypes = request.headers().get(HttpHeaders.CONTENT_TYPE); MediaType requestContentType = null; if (contentTypes != null && !contentTypes.isEmpty()) { String type = contentTypes.iterator().next(); requestContentType = MediaType.valueOf(type); } for (HttpMessageConverter<?> messageConverter : this.messageConverters.getObject().getConverters()) { if (messageConverter.canWrite(requestType, requestContentType)) { FeignOutputMessage outputMessage = new FeignOutputMessage(request); try { @SuppressWarnings("unchecked") HttpMessageConverter<Object> copy = (HttpMessageConverter<Object>) messageConverter; copy.write(requestBody, requestContentType, outputMessage); } catch (IOException ex) { throw new EncodeException("Error converting request body", ex); } request.headers(null); request.headers(FeignUtils.getHeaders(outputMessage.getHeaders())); request.body(outputMessage.getOutputStream().toByteArray(), Charset.forName("UTF-8")); // TODO: return; } } String message = "Could not write request: no suitable HttpMessageConverter " + "found for request type [" + requestType.getName() + "]"; if (requestContentType != null) { message += " and content type [" + requestContentType + "]"; } throw new EncodeException(message); } }
@Bean public RestTemplate createRestTemplate() { RestTemplate restTemplate = new RestTemplate(); List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter(); jsonMessageConverter.setObjectMapper(objectMapper); messageConverters.add(jsonMessageConverter); restTemplate.setMessageConverters(messageConverters); return restTemplate; }
/** * Constructor * @param response Spring response entity (not null) * @param type Response type (not null) * @param messageConverters HTTP message converters * @param propertySet Optional {@link PropertySet} to use to deserialize a {@link PropertyBox} */ public SpringResponseEntity(org.springframework.http.ResponseEntity<Resource> response, ResponseType<T> type, List<HttpMessageConverter<?>> messageConverters, PropertySet<?> propertySet) { super(); ObjectUtils.argumentNotNull(response, "ClientHttpResponse must be not null"); ObjectUtils.argumentNotNull(type, "Response type must be not null"); this.response = response; this.type = type; this.messageConverters = (messageConverters != null) ? messageConverters : Collections.emptyList(); this.propertySet = propertySet; this.httpResponse = new StreamHttpResponse(response); }
@Bean public HttpMessageConverters fastJsonHttpMessageConverters() { FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); //处理中文乱码 List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); fastConverter.setSupportedMediaTypes(fastMediaTypes); return new HttpMessageConverters((HttpMessageConverter<?>) fastConverter); }
@Bean public HttpMessageConverter customJackson2HttpMessageConverter() { return new FastJsonHttpMessageConverter4() { @Override protected void writeInternal(Object obj, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { if (obj instanceof ResultModel) { super.writeInternal(obj, type, outputMessage); } else { super.writeInternal(ResultResolver.sendNormalResult(obj), type, outputMessage); } } }; }
private List<HttpMessageConverter<?>> getFormPartsMessageConverters() { List<HttpMessageConverter<?>> partConverters = new ArrayList<HttpMessageConverter<?>>(); StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(); stringConverter.setSupportedMediaTypes(Collections.singletonList(JsonUtil.JSON_MEDIA_TYPE)); stringConverter.setWriteAcceptCharset(false); partConverters.add(stringConverter); partConverters.add(new ResourceHttpMessageConverter()); partConverters.add(new UploadApplicationPayloadHttpMessageConverter()); return partConverters; }
private List<HttpMessageConverter<?>> getHttpMessageConverters() { List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>(); messageConverters.add(new ByteArrayHttpMessageConverter()); messageConverters.add(new StringHttpMessageConverter()); messageConverters.add(new ResourceHttpMessageConverter()); messageConverters.add(new UploadApplicationPayloadHttpMessageConverter()); messageConverters.add(getFormHttpMessageConverter()); messageConverters.add(new MappingJackson2HttpMessageConverter()); messageConverters.add(new LoggregatorHttpMessageConverter()); return messageConverters; }
protected AbstractZg2proRestTemplate(@Nullable List<HttpMessageConverter<?>> lConverters, @Nullable List<ClientHttpRequestInterceptor> lInterceptors) { super(); this.setErrorHandler(new RestTemplateErrorHandler()); if (!CollectionUtils.isEmpty(lConverters)) { //emptiness is rechecked inside setMessageConverters but it may change //in a future spring release setMessageConverters(lConverters); } if (lInterceptors == null) { lInterceptors = new ArrayList<>(); } }
/** * 消息转换 * * @param converters */ @Override public void extendMessageConverters ( List< HttpMessageConverter< ? > > converters ) { // 默认转换器注册后, 插入自定义的请求响应转换器 converters.add( new StringHttpMessageConverter( StandardCharsets.UTF_8 ) ); converters.add( this.mappingJackson2HttpMessageConverter() ); }
@Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { // See SPR-7316,for weixin token verify.fastjson will convert string 123 to "123" StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(); stringHttpMessageConverter.setWriteAcceptCharset(false); converters.add(stringHttpMessageConverter); converters.add(new ByteArrayHttpMessageConverter()); converters.add(fastJsonHttpMessageConverter()); }
@Autowired public void setRestTemplate(TestRestTemplate testRestTemplate) { List<HttpMessageConverter<?>> messageConverters = testRestTemplate.getRestTemplate().getMessageConverters(); messageConverters.add(0, new YamlJackson2HttpMessageConverter()); messageConverters.add(0, new JsonJackson2HttpMessageConverter()); messageConverters.add( 0, new ByteArrayHttpMessageConverter()); this.restTemplate = testRestTemplate; }
@Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); final ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.registerModule(new JavaTimeModule()); converter.setObjectMapper(objectMapper); converters.add(converter); super.configureMessageConverters(converters); }
/** * Get a registered GsonHttpMessageConverter from RestTemplate * @param restTemplate RestTemplate * @return Optional GsonHttpMessageConverter, empty if not registered */ private static Optional<GsonHttpMessageConverter> getGsonConverter(RestTemplate restTemplate) { for (HttpMessageConverter<?> converter : restTemplate.getMessageConverters()) { if (GsonHttpMessageConverter.class.isAssignableFrom(converter.getClass())) { return Optional.of((GsonHttpMessageConverter) converter); } } return Optional.empty(); }
/** * Get a registered AbstractJackson2HttpMessageConverter from RestTemplate * @param restTemplate RestTemplate * @return Optional AbstractJackson2HttpMessageConverter, empty if not registered */ private static Optional<AbstractJackson2HttpMessageConverter> getJacksonConverter(RestTemplate restTemplate) { for (HttpMessageConverter<?> converter : restTemplate.getMessageConverters()) { if (AbstractJackson2HttpMessageConverter.class.isAssignableFrom(converter.getClass())) { return Optional.of((AbstractJackson2HttpMessageConverter) converter); } } return Optional.empty(); }
public SpringParameterProvider(ConfigurableBeanFactory beanFactory, HttpServletRequest request) { this.request = request; this.beanFactory = beanFactory; List<HttpMessageConverter<?>> messageConverters = getHttpMessageConverters(); argumentResolvers = new HandlerMethodArgumentResolverComposite() .addResolvers(getArgumentResolvers(messageConverters)); }
private List<HttpMessageConverter<?>> getHttpMessageConverters() { StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(); stringHttpMessageConverter.setWriteAcceptCharset(false); // see SPR-7316 List<HttpMessageConverter<?>> converters = new ArrayList<>(4); converters.add(new ByteArrayHttpMessageConverter()); converters.add(stringHttpMessageConverter); converters.add(new SourceHttpMessageConverter<>()); converters.add(new AllEncompassingFormHttpMessageConverter()); return converters; }
private List<HandlerMethodArgumentResolver> getArgumentResolvers(List<HttpMessageConverter<?>> messageConverters) { List<HandlerMethodArgumentResolver> resolvers = new LinkedList<>(); resolvers.add(new RequestParamMethodArgumentResolver(beanFactory, false)); resolvers.add(new RequestParamMapMethodArgumentResolver()); resolvers.add(new MatrixVariableMethodArgumentResolver()); resolvers.add(new MatrixVariableMapMethodArgumentResolver()); resolvers.add(new ServletModelAttributeMethodProcessor(false)); resolvers.add(new RequestResponseBodyMethodProcessor(messageConverters)); resolvers.add(new RequestPartMethodArgumentResolver(messageConverters)); resolvers.add(new RequestHeaderMethodArgumentResolver(beanFactory)); resolvers.add(new RequestHeaderMapMethodArgumentResolver()); resolvers.add(new ServletCookieValueMethodArgumentResolver(beanFactory)); resolvers.add(new ExpressionValueMethodArgumentResolver(beanFactory)); resolvers.add(new ServletRequestMethodArgumentResolver()); resolvers.add(new ServletResponseMethodArgumentResolver()); resolvers.add(new HttpEntityMethodProcessor(messageConverters)); resolvers.add(new RedirectAttributesMethodArgumentResolver()); resolvers.add(new ModelMethodProcessor()); resolvers.add(new MapMethodProcessor()); resolvers.add(new ErrorsMethodArgumentResolver()); resolvers.add(new SessionStatusMethodArgumentResolver()); resolvers.add(new UriComponentsBuilderMethodArgumentResolver()); resolvers.add(new RequestParamMethodArgumentResolver(beanFactory, true)); resolvers.add(new ServletModelAttributeMethodProcessor(true)); return resolvers; }