org.springframework.http.converter.HttpMessageConverter Java Examples

The following examples show how to use org.springframework.http.converter.HttpMessageConverter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpMessageConverterExtractorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test  // SPR-13592
@SuppressWarnings("unchecked")
public void converterThrowsIOException() throws IOException {
	HttpMessageConverter<String> converter = mock(HttpMessageConverter.class);
	HttpHeaders responseHeaders = new HttpHeaders();
	MediaType contentType = MediaType.TEXT_PLAIN;
	responseHeaders.setContentType(contentType);
	extractor = new HttpMessageConverterExtractor<>(String.class, createConverterList(converter));
	given(response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream("Foobar".getBytes()));
	given(converter.canRead(String.class, contentType)).willReturn(true);
	given(converter.read(eq(String.class), any(HttpInputMessage.class))).willThrow(IOException.class);
	assertThatExceptionOfType(RestClientException.class).isThrownBy(() ->
			extractor.extractData(response))
		.withMessageContaining("Error while extracting response for type [class java.lang.String] and content type [text/plain]")
		.withCauseInstanceOf(IOException.class);
}
 
Example #2
Source File: ParamEncryptRequestBodyAdvice.java    From open-capacity-platform with Apache License 2.0 6 votes vote down vote up
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter,
		Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
	try {
		boolean encode = false;
		if (methodParameter.getMethod().isAnnotationPresent(SecurityParameter.class)) {
			SecurityParameter serializedField = (SecurityParameter) methodParameter
					.getMethodAnnotation(SecurityParameter.class);
			encode = serializedField.inDecode();
		}

		if (encode) {
			log.info("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行解密");
			 return new ParamEncryptRequestBodyAdvice.DefaultHttpInputMessage(httpInputMessage);
		} else {
			return httpInputMessage;
		}
	} catch (Exception e) {
		log.error(
				"对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行解密出现异常:" + e.getMessage());
	}
	 return httpInputMessage;
}
 
Example #3
Source File: WebConfig.java    From cf-SpringBootTrader with Apache License 2.0 6 votes vote down vote up
/**
 * configure the message converters with the date formatter.
 */
@Override
public void configureMessageConverters(
		List<HttpMessageConverter<?>> converters) {
	// Configure JSON support
	MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
	mappingJacksonHttpMessageConverter.setSupportedMediaTypes(Arrays
			.asList(MediaType.APPLICATION_JSON));
	//mappingJacksonHttpMessageConverter.getObjectMapper().configure(
	//		Feature.WRITE_DATES_AS_TIMESTAMPS, true);
	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
	// There is no need to set the timezone as Jackson uses GMT and not the
	// local time zone (which is exactly what you want)
	// Note: While SimpleDateFormat is not threadsafe, Jackson Marshaller's
	// StdSerializerProvider clones the configured formatter for each thread
	mappingJacksonHttpMessageConverter.getObjectMapper().setDateFormat(
			format);
	//mappingJacksonHttpMessageConverter.getObjectMapper().configure(
	//		Feature.INDENT_OUTPUT, true);
	// mappingJacksonHttpMessageConverter.getObjectMapper().getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
	converters.add(mappingJacksonHttpMessageConverter);
}
 
Example #4
Source File: RestTemplateFactory.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
public static RestOperations createCommonsHttpRestTemplate(int maxConnPerRoute, int maxConnTotal,
                                                           int connectTimeout, int soTimeout, int retryTimes, RetryPolicyFactory retryPolicyFactory) {
    HttpClient httpClient = HttpClientBuilder.create()
            .setMaxConnPerRoute(maxConnPerRoute)
            .setMaxConnTotal(maxConnTotal)
            .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(soTimeout).build())
            .setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(connectTimeout).build())
            .build();
    ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
    RestTemplate restTemplate = new RestTemplate(factory);
    //set jackson mapper
    for (HttpMessageConverter<?> hmc : restTemplate.getMessageConverters()) {
        if (hmc instanceof MappingJackson2HttpMessageConverter) {
            ObjectMapper objectMapper = createObjectMapper();
            MappingJackson2HttpMessageConverter mj2hmc = (MappingJackson2HttpMessageConverter) hmc;
            mj2hmc.setObjectMapper(objectMapper);
        }
    }

    return (RestOperations) Proxy.newProxyInstance(RestOperations.class.getClassLoader(),
            new Class[]{RestOperations.class},
            new RetryableRestOperationsHandler(restTemplate, retryTimes, retryPolicyFactory));
}
 
Example #5
Source File: AnnotationDrivenBeanDefinitionParserTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void verifyMessageConverters(Object bean, boolean hasDefaultRegistrations) {
	assertNotNull(bean);
	Object value = new DirectFieldAccessor(bean).getPropertyValue("messageConverters");
	assertNotNull(value);
	assertTrue(value instanceof List);
	List<HttpMessageConverter<?>> converters = (List<HttpMessageConverter<?>>) value;
	if (hasDefaultRegistrations) {
		assertTrue("Default and custom converter expected", converters.size() > 2);
	}
	else {
		assertTrue("Only custom converters expected", converters.size() == 2);
	}
	assertTrue(converters.get(0) instanceof StringHttpMessageConverter);
	assertTrue(converters.get(1) instanceof ResourceHttpMessageConverter);
}
 
Example #6
Source File: SmartRestTemplateConfig.java    From smart-admin with MIT License 6 votes vote down vote up
/**
 * fastJsonRestTemplate
 *
 * @return
 */
@Bean(name = "fastJsonRestTemplate")
public RestTemplate fastJsonRestTemplate() {
    RestTemplate restTemplate = new RestTemplate(httpRequestFactory());

    HttpMessageConverter<?> converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));

    FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
    List<MediaType> fastMediaTypes = new ArrayList<>();
    fastMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
    fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
    fastConverter.setSupportedMediaTypes(fastMediaTypes);
    List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
    converters.add(1,converter);
    converters.add(fastConverter);
    return restTemplate;
}
 
Example #7
Source File: HttpMessageConverterExtractorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void generics() throws IOException {
	GenericHttpMessageConverter<String> converter = mock(GenericHttpMessageConverter.class);
	List<HttpMessageConverter<?>> converters = createConverterList(converter);
	HttpHeaders responseHeaders = new HttpHeaders();
	MediaType contentType = MediaType.TEXT_PLAIN;
	responseHeaders.setContentType(contentType);
	String expected = "Foo";
	ParameterizedTypeReference<List<String>> reference = new ParameterizedTypeReference<List<String>>() {};
	Type type = reference.getType();
	extractor = new HttpMessageConverterExtractor<List<String>>(type, converters);
	given(response.getStatusCode()).willReturn(HttpStatus.OK);
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream(expected.getBytes()));
	given(converter.canRead(type, null, contentType)).willReturn(true);
	given(converter.read(eq(type), eq(null), any(HttpInputMessage.class))).willReturn(expected);

	Object result = extractor.extractData(response);

	assertEquals(expected, result);
}
 
Example #8
Source File: RequestMappingHandlerAdapterTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void responseBodyAdvice() throws Exception {
	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new MappingJackson2HttpMessageConverter());
	this.handlerAdapter.setMessageConverters(converters);

	this.webAppContext.registerSingleton("rba", ResponseCodeSuppressingAdvice.class);
	this.webAppContext.refresh();

	this.request.addHeader("Accept", MediaType.APPLICATION_JSON_VALUE);
	this.request.setParameter("c", "callback");

	HandlerMethod handlerMethod = handlerMethod(new SimpleController(), "handleBadRequest");
	this.handlerAdapter.afterPropertiesSet();
	this.handlerAdapter.handle(this.request, this.response, handlerMethod);

	assertEquals(200, this.response.getStatus());
	assertEquals("{\"status\":400,\"message\":\"body\"}", this.response.getContentAsString());
}
 
Example #9
Source File: JSONPResponseBodyAdvice.java    From uavstack with Apache License 2.0 6 votes vote down vote up
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                              Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                              ServerHttpResponse response) {

    ResponseJSONP responseJsonp = returnType.getMethodAnnotation(ResponseJSONP.class);
    if(responseJsonp == null){
        responseJsonp = returnType.getContainingClass().getAnnotation(ResponseJSONP.class);
    }

    HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
    String callbackMethodName = servletRequest.getParameter(responseJsonp.callback());

    if (!IOUtils.isValidJsonpQueryParam(callbackMethodName)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invalid jsonp parameter value:" + callbackMethodName);
        }
        callbackMethodName = null;
    }

    JSONPObject jsonpObject = new JSONPObject(callbackMethodName);
    jsonpObject.addParameter(body);
    beforeBodyWriteInternal(jsonpObject, selectedContentType, returnType, request, response);
    return jsonpObject;
}
 
Example #10
Source File: DefaultServerRequest.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> T bodyInternal(Type bodyType, Class<?> bodyClass)
		throws ServletException, IOException {

	MediaType contentType =
			this.headers.contentType().orElse(MediaType.APPLICATION_OCTET_STREAM);

	for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
		if (messageConverter instanceof GenericHttpMessageConverter) {
			GenericHttpMessageConverter<T> genericMessageConverter =
					(GenericHttpMessageConverter<T>) messageConverter;
			if (genericMessageConverter.canRead(bodyType, bodyClass, contentType)) {
				return genericMessageConverter.read(bodyType, bodyClass, this.serverHttpRequest);
			}
		}
		if (messageConverter.canRead(bodyClass, contentType)) {
			HttpMessageConverter<T> theConverter =
					(HttpMessageConverter<T>) messageConverter;
			Class<? extends T> clazz = (Class<? extends T>) bodyClass;
			return theConverter.read(clazz, this.serverHttpRequest);
		}
	}
	throw new HttpMediaTypeNotSupportedException(contentType, this.allSupportedMediaTypes);
}
 
Example #11
Source File: RequestPartIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
	ByteArrayHttpMessageConverter emptyBodyConverter = new ByteArrayHttpMessageConverter();
	emptyBodyConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));

	List<HttpMessageConverter<?>> converters = new ArrayList<>(3);
	converters.add(emptyBodyConverter);
	converters.add(new ByteArrayHttpMessageConverter());
	converters.add(new ResourceHttpMessageConverter());
	converters.add(new MappingJackson2HttpMessageConverter());

	AllEncompassingFormHttpMessageConverter converter = new AllEncompassingFormHttpMessageConverter();
	converter.setPartConverters(converters);

	restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
	restTemplate.setMessageConverters(Collections.singletonList(converter));
}
 
Example #12
Source File: ServletAnnotationControllerHandlerMethodTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test // SPR-16172
public void httpEntityWithContentType() throws Exception {
	initServlet(wac -> {
		RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
		List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
		messageConverters.add(new MappingJackson2HttpMessageConverter());
		messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
		adapterDef.getPropertyValues().add("messageConverters", messageConverters);
		wac.registerBeanDefinition("handlerAdapter", adapterDef);
	}, ResponseEntityController.class);

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test-entity");
	MockHttpServletResponse response = new MockHttpServletResponse();
	getServlet().service(request, response);
	assertEquals(200, response.getStatus());
	assertEquals("application/xml", response.getHeader("Content-Type"));
	assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
					"<testEntity><name>Foo Bar</name></testEntity>", response.getContentAsString());
}
 
Example #13
Source File: XpathRequestMatchersIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Before
public void setup() {
	List<Person> composers = Arrays.asList(
			new Person("Johann Sebastian Bach").setSomeDouble(21),
			new Person("Johannes Brahms").setSomeDouble(.0025),
			new Person("Edvard Grieg").setSomeDouble(1.6035),
			new Person("Robert Schumann").setSomeDouble(Double.NaN));

	List<Person> performers = Arrays.asList(
			new Person("Vladimir Ashkenazy").setSomeBoolean(false),
			new Person("Yehudi Menuhin").setSomeBoolean(true));

	this.people = new PeopleWrapper(composers, performers);

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new Jaxb2RootElementHttpMessageConverter());

	this.restTemplate = new RestTemplate();
	this.restTemplate.setMessageConverters(converters);

	this.mockServer = MockRestServiceServer.createServer(this.restTemplate);
}
 
Example #14
Source File: WebMvcConfig.java    From spring-boot-cookbook with Apache License 2.0 6 votes vote down vote up
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    FastJsonHttpMessageConverter httpMessageConverter = new FastJsonHttpMessageConverter();
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    fastJsonConfig.setSerializerFeatures(SerializerFeature.QuoteFieldNames,
            SerializerFeature.WriteEnumUsingToString,
            SerializerFeature.WriteMapNullValue,
            SerializerFeature.WriteDateUseDateFormat);
    fastJsonConfig.setSerializeFilters(new ValueFilter() {
        @Override
        public Object process(Object o, String s, Object source) {
            if (source == null) {
                return "";
            }
            if (source instanceof Date) {
                return ((Date) source).getTime();
            }
            return source;
        }
    });
    httpMessageConverter.setFastJsonConfig(fastJsonConfig);
    converters.add(httpMessageConverter);
}
 
Example #15
Source File: DubboTransporterInterceptor.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
public DubboTransporterInterceptor(
		DubboServiceMetadataRepository dubboServiceMetadataRepository,
		List<HttpMessageConverter<?>> messageConverters, ClassLoader classLoader,
		Map<String, Object> dubboTranslatedAttributes,
		DubboGenericServiceFactory serviceFactory,
		DubboGenericServiceExecutionContextFactory contextFactory) {
	this.repository = dubboServiceMetadataRepository;
	this.dubboTranslatedAttributes = dubboTranslatedAttributes;
	this.clientHttpResponseFactory = new DubboClientHttpResponseFactory(
			messageConverters, classLoader);
	this.serviceFactory = serviceFactory;
	this.contextFactory = contextFactory;
}
 
Example #16
Source File: JsonRpcRestClient.java    From jsonrpc4j with MIT License 5 votes vote down vote up
/**
 * Check RestTemplate contains required converters
 */
private void initRestTemplate() {

	boolean isContainsConverter = false;
	for (HttpMessageConverter<?> httpMessageConverter : this.restTemplate.getMessageConverters()) {
		if (MappingJacksonRPC2HttpMessageConverter.class.isAssignableFrom(httpMessageConverter.getClass())) {
			isContainsConverter = true;
			break;
		}
	}

	if (!isContainsConverter) {

		final MappingJacksonRPC2HttpMessageConverter messageConverter = new MappingJacksonRPC2HttpMessageConverter();
		messageConverter.setObjectMapper(this.getObjectMapper());

		final List<HttpMessageConverter<?>> restMessageConverters = new ArrayList<>();
		restMessageConverters.addAll(this.restTemplate.getMessageConverters());
		// Place JSON-RPC converter on the first place!
		restMessageConverters.add(0, messageConverter);

		this.restTemplate.setMessageConverters(restMessageConverters);
	}

	// use specific JSON-RPC error handler if it has not been changed to custom 
	if (restTemplate.getErrorHandler() instanceof org.springframework.web.client.DefaultResponseErrorHandler) {
		restTemplate.setErrorHandler(JsonRpcResponseErrorHandler.INSTANCE);
	}
}
 
Example #17
Source File: AtomClientTest.java    From microservice-atom with Apache License 2.0 5 votes vote down vote up
private Feed retrieveFeed() {
	for (HttpMessageConverter<?> converter : restTemplate.getMessageConverters()) {
		System.out.println(converter);
	}
	Feed feed = restTemplate.getForEntity(feedUrl(), Feed.class).getBody();
	return feed;
}
 
Example #18
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-13423
public void handleReturnValueCharSequence() throws Exception {
	List<HttpMessageConverter<?>>converters = new ArrayList<>();
	converters.add(new ByteArrayHttpMessageConverter());
	converters.add(new StringHttpMessageConverter());

	Method method = ResponseBodyController.class.getMethod("handleWithCharSequence");
	MethodParameter returnType = new MethodParameter(method, -1);

	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);
	processor.handleReturnValue(new StringBuilder("Foo"), returnType, container, request);

	assertEquals("text/plain;charset=ISO-8859-1", servletResponse.getHeader("Content-Type"));
	assertEquals("Foo", servletResponse.getContentAsString());
}
 
Example #19
Source File: CometCollectorResponseBodyAdvice.java    From Milkomeda with MIT License 5 votes vote down vote up
@Override
public Object beforeBodyWrite(Object body, @NonNull MethodParameter returnType, @NonNull MediaType selectedContentType,
                              @NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
                              @NonNull ServerHttpRequest request, @NonNull ServerHttpResponse response) {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes instanceof ServletRequestAttributes) {
        ((ServletRequestAttributes) requestAttributes).getRequest().setAttribute(REQUEST_ATTRIBUTE_BODY, body);
    }
    return body;
}
 
Example #20
Source File: WebConfig.java    From sanshanblog with Apache License 2.0 5 votes vote down vote up
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
    FastJsonConfig config = new FastJsonConfig();
    config.setDateFormat("yyyy-MM-dd HH:mm:ss");
    fastJsonHttpMessageConverter.setFastJsonConfig(config);
    converters.add(fastJsonHttpMessageConverter);
    converters.add(resourceHttpMessageConverter);
    super.configureMessageConverters(converters);
}
 
Example #21
Source File: SpringParameterProvider.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #22
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-12501
public void resolveHttpEntityArgumentWithJacksonJsonViewAndXmlMessageConverter() throws Exception {
	String content = "<root>" +
			"<withView1>with</withView1>" +
			"<withView2>with</withView2>" +
			"<withoutView>without</withoutView></root>";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_XML_VALUE);

	Method method = JacksonController.class.getMethod("handleHttpEntity", HttpEntity.class);
	HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
	MethodParameter methodParameter = handlerMethod.getMethodParameters()[0];

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new MappingJackson2XmlHttpMessageConverter());

	HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(
			converters, null, Collections.singletonList(new JsonViewRequestBodyAdvice()));

	@SuppressWarnings("unchecked")
	HttpEntity<JacksonViewBean> result = (HttpEntity<JacksonViewBean>)
			processor.resolveArgument(methodParameter, this.container, this.request, this.factory);

	assertNotNull(result);
	assertNotNull(result.getBody());
	assertEquals("with", result.getBody().getWithView1());
	assertNull(result.getBody().getWithView2());
	assertNull(result.getBody().getWithoutView());
}
 
Example #23
Source File: RestTemplate.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Set the message body converters to use.
 * <p>These converters are used to convert from and to HTTP requests and responses.
 */
public void setMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
	Assert.notEmpty(messageConverters, "At least one HttpMessageConverter required");
	// Take getMessageConverters() List as-is when passed in here
	if (this.messageConverters != messageConverters) {
		this.messageConverters.clear();
		this.messageConverters.addAll(messageConverters);
	}
}
 
Example #24
Source File: MvcConfigurer.java    From spring-boot-api-project-seed with Apache License 2.0 5 votes vote down vote up
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    //使用阿里 FastJson 作为JSON MessageConverter
    FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
    FastJsonConfig config = new FastJsonConfig();
    //保留空的字段
    config.setSerializerFeatures(SerializerFeature.WriteMapNullValue);
    // 按需配置,更多参考FastJson文档
    converter.setFastJsonConfig(config);
    converter.setDefaultCharset(Charset.forName("UTF-8"));
    converters.add(converter);
}
 
Example #25
Source File: RequestResponseBodyMethodProcessorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void handleReturnValueStringAcceptCharset() throws Exception {
	this.servletRequest.addHeader("Accept", "text/plain;charset=UTF-8");

	List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
	converters.add(new ByteArrayHttpMessageConverter());
	converters.add(new StringHttpMessageConverter());
	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);

	processor.writeWithMessageConverters("Foo", returnTypeString, webRequest);

	assertEquals("text/plain;charset=UTF-8", servletResponse.getHeader("Content-Type"));
}
 
Example #26
Source File: HttpClientConfig.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private List<HttpMessageConverter<?>> converters() {
  List<HttpMessageConverter<?>> result = Lists.newArrayList();
  result.add(new ByteArrayHttpMessageConverter());
  result.add(new StringHttpMessageConverter());
  result.add(new ResourceHttpMessageConverter());
  result.add(new SourceHttpMessageConverter<>());
  result.add(new AllEncompassingFormHttpMessageConverter());
  result.add(new Jaxb2RootElementHttpMessageConverter());
  result.add(gsonHttpMessageConverter);
  return result;
}
 
Example #27
Source File: RestController.java    From telekom-workflow-engine with MIT License 5 votes vote down vote up
@PostConstruct
public void init(){
    for (HttpMessageConverter converter : adapter.getMessageConverters()) {
        if (converter instanceof GsonHttpMessageConverter) {
            Gson gson = new GsonBuilder().serializeNulls().create();
            ((GsonHttpMessageConverter)converter).setGson(gson);
        }
    }
}
 
Example #28
Source File: HttpMessageConverterResolver.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
/**
 * Return the media types supported by all provided message converters sorted by
 * specificity via {@link MediaType#sortBySpecificity(List)}.
 * @param messageConverters list of converters
 * @return list of MediaTypes
 */
private List<MediaType> getAllSupportedMediaTypes(
		List<HttpMessageConverter<?>> messageConverters) {
	Set<MediaType> allSupportedMediaTypes = new LinkedHashSet<MediaType>();
	for (HttpMessageConverter<?> messageConverter : messageConverters) {
		allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes());
	}
	List<MediaType> result = new ArrayList<MediaType>(allSupportedMediaTypes);
	MediaType.sortBySpecificity(result);
	return unmodifiableList(result);
}
 
Example #29
Source File: ServletInvocableHandlerMethodTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void wrapConcurrentResult_ResponseEntity() throws Exception {
	List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
	converters.add(new StringHttpMessageConverter());
	this.returnValueHandlers.addHandler(new HttpEntityMethodProcessor(converters));
	ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new ResponseEntityHandler(), "handleDeferred");
	handlerMethod = handlerMethod.wrapConcurrentResult(new ResponseEntity<>("bar", HttpStatus.OK));
	handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer);

	assertEquals("bar", this.response.getContentAsString());
}
 
Example #30
Source File: ResponseBodyEmitterReturnValueHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {

	List<HttpMessageConverter<?>> converters = Arrays.asList(
			new StringHttpMessageConverter(), new MappingJackson2HttpMessageConverter());

	this.handler = new ResponseBodyEmitterReturnValueHandler(converters);
	this.request = new MockHttpServletRequest();
	this.response = new MockHttpServletResponse();
	this.webRequest = new ServletWebRequest(this.request, this.response);

	AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response);
	WebAsyncUtils.getAsyncManager(this.webRequest).setAsyncWebRequest(asyncWebRequest);
	this.request.setAsyncSupported(true);
}