Java Code Examples for org.springframework.http.converter.StringHttpMessageConverter

The following examples show how to use org.springframework.http.converter.StringHttpMessageConverter. These examples are extracted from open source projects. 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 Project: seed   Source File: RestTemplateConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean(RestTemplate.class)
public RestTemplate getRestTemplate(){
    RestTemplate restTemplate = new RestTemplate(this.createFactory());
    //解决中文乱码问题
    //由于RestTemplate.postForObject()使用的StringHttpMessageConverter默认编码是ISO-8859-1,所以中文会乱码
    //所以我们要移除默认的StringHttpMessageConverter,再添加新的由UTF-8编码的StringHttpMessageConverter
    List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
    HttpMessageConverter<?> converterTarget = null;
    for(HttpMessageConverter<?> item : converterList){
        if(StringHttpMessageConverter.class == item.getClass()){
            converterTarget = item;
            break;
        }
    }
    if(null != converterTarget){
        converterList.remove(converterTarget);
    }
    converterList.add(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
    //由于converterList是restTemplate对象的全局变量的引用
    //所以不用restTemplate.setMessageConverters(converterList);
    return restTemplate;
}
 
Example 2
Source Project: spring-analysis-note   Source File: RouterFunctionMapping.java    License: MIT License 6 votes vote down vote up
/**
 * Initializes a default set of {@linkplain HttpMessageConverter message converters}.
 */
private void initMessageConverters() {
	List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(4);
	messageConverters.add(new ByteArrayHttpMessageConverter());
	messageConverters.add(new StringHttpMessageConverter());

	try {
		messageConverters.add(new SourceHttpMessageConverter<>());
	}
	catch (Error err) {
		// Ignore when no TransformerFactory implementation is available
	}
	messageConverters.add(new AllEncompassingFormHttpMessageConverter());

	this.messageConverters = messageConverters;
}
 
Example 3
Source Project: java-platform   Source File: WebConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
	StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
	stringConverter.setWriteAcceptCharset(false);

	converters.add(new ByteArrayHttpMessageConverter());
	converters.add(stringConverter);
	converters.add(new ResourceHttpMessageConverter());
	converters.add(new SourceHttpMessageConverter<Source>());
	converters.add(new AllEncompassingFormHttpMessageConverter());
}
 
Example 4
@Test  // SPR-6877
public void overlappingMessageConvertersRequestBody() throws Exception {
	initServlet(wac -> {
		RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
		List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
		messageConverters.add(new StringHttpMessageConverter());
		messageConverters
				.add(new SimpleMessageConverter(new MediaType("application","json"), MediaType.ALL));
		adapterDef.getPropertyValues().add("messageConverters", messageConverters);
		wac.registerBeanDefinition("handlerAdapter", adapterDef);
	}, RequestResponseBodyController.class);

	MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something");
	request.setContent("Hello World".getBytes("UTF-8"));
	request.addHeader("Content-Type", "text/plain; charset=utf-8");
	request.addHeader("Accept", "application/json, text/javascript, */*");
	MockHttpServletResponse response = new MockHttpServletResponse();
	getServlet().service(request, response);
	assertEquals("Invalid content-type", "application/json;charset=ISO-8859-1", response.getHeader("Content-Type"));
}
 
Example 5
Source Project: Jpom   Source File: JpomApplication.java    License: MIT License 6 votes vote down vote up
public JpomApplication(Type appType, Class<?> appClass, String[] args) throws Exception {
    super(appClass);
    //
    checkEvent(args);
    JpomApplication.appType = appType;
    JpomApplication.appClass = appClass;
    JpomApplication.args = args;

    addHttpMessageConverter(new StringHttpMessageConverter(CharsetUtil.CHARSET_UTF_8));

    //
    ObjectMapper build = createJackson();
    addHttpMessageConverter(new MappingJackson2HttpMessageConverter(build));

    // 参数拦截器
    addInterceptor(ParameterInterceptor.class);
    addInterceptor(PluginFeatureInterceptor.class);
    //
    addApplicationEventClient(new JpomApplicationEvent());
    // 添加初始化监听
    this.application().addInitializers(new PluginFactory());
}
 
Example 6
@Test  // SPR-13423
public void handleReturnValueCharSequence() throws Exception {
	List<HttpMessageConverter<?>>converters = new ArrayList<>();
	converters.add(new ByteArrayHttpMessageConverter());
	converters.add(new StringHttpMessageConverter());

	Method method = getClass().getDeclaredMethod("handle");
	MethodParameter returnType = new MethodParameter(method, -1);
	ResponseEntity<StringBuilder> returnValue = ResponseEntity.ok(new StringBuilder("Foo"));

	HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(converters);
	processor.handleReturnValue(returnValue, returnType, mavContainer, webRequest);

	assertEquals("text/plain;charset=ISO-8859-1", servletResponse.getHeader("Content-Type"));
	assertEquals("Foo", servletResponse.getContentAsString());
}
 
Example 7
@Before
public void setUp() throws Exception {

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

	this.handler = new ResponseBodyEmitterReturnValueHandler(converters);
	this.mavContainer = new ModelAndViewContainer();

	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);
}
 
Example 8
Source Project: spring-boot-chatbot   Source File: RestTemplateFactory.java    License: MIT License 6 votes vote down vote up
public static RestOperations getRestOperations(HttpComponentsClientHttpRequestFactory factory) {
    RestTemplate restTemplate = new RestTemplate(factory);

    StringHttpMessageConverter stringMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
    MappingJackson2HttpMessageConverter jackson2Converter = new MappingJackson2HttpMessageConverter();
    ByteArrayHttpMessageConverter byteArrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
    FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
    formHttpMessageConverter.setCharset(Charset.forName("UTF-8"));

    List<HttpMessageConverter<?>> converters = new ArrayList<>();
    converters.add(jackson2Converter);
    converters.add(stringMessageConverter);
    converters.add(byteArrayHttpMessageConverter);
    converters.add(formHttpMessageConverter);

    restTemplate.setMessageConverters(converters);
    return restTemplate;
}
 
Example 9
@Test  // SPR-6877
public void overlappingMessageConvertersRequestBody() throws Exception {
	initServlet(wac -> {
		RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
		List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
		messageConverters.add(new StringHttpMessageConverter());
		messageConverters
				.add(new SimpleMessageConverter(new MediaType("application","json"), MediaType.ALL));
		adapterDef.getPropertyValues().add("messageConverters", messageConverters);
		wac.registerBeanDefinition("handlerAdapter", adapterDef);
	}, RequestResponseBodyController.class);

	MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something");
	request.setContent("Hello World".getBytes("UTF-8"));
	request.addHeader("Content-Type", "text/plain; charset=utf-8");
	request.addHeader("Accept", "application/json, text/javascript, */*");
	MockHttpServletResponse response = new MockHttpServletResponse();
	getServlet().service(request, response);
	assertEquals("Invalid content-type", "application/json;charset=ISO-8859-1", response.getHeader("Content-Type"));
}
 
Example 10
@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 11
/**
 * 自定义消息转换器:使用 Fastjson 替换 Spring Boot 默认使用的 Jackson
 *
 * @param converters 消息转换器
 */
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    // 清除默认 Json 转换器
    converters.removeIf(converter -> converter instanceof MappingJackson2HttpMessageConverter);

    // 配置 FastJson
    FastJsonConfig config = new FastJsonConfig();
    config.setSerializerFeatures(SerializerFeature.QuoteFieldNames, SerializerFeature.WriteEnumUsingToString,
        SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat);

    // 添加 FastJsonHttpMessageConverter
    FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
    fastJsonHttpMessageConverter.setFastJsonConfig(config);
    List<MediaType> fastMediaTypes = new ArrayList<>();
    fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
    fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
    converters.add(fastJsonHttpMessageConverter);

    // 添加 StringHttpMessageConverter,解决中文乱码问题
    StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
    converters.add(stringHttpMessageConverter);


}
 
Example 12
Source Project: nakadi   Source File: PostSubscriptionControllerTest.java    License: MIT License 6 votes vote down vote up
public PostSubscriptionControllerTest() throws Exception {

        when(featureToggleService.isFeatureEnabled(any())).thenReturn(true);
        when(featureToggleService.isFeatureEnabled(Feature.DISABLE_SUBSCRIPTION_CREATION))
                .thenReturn(false);

        when(applicationService.exists(any())).thenReturn(true);

        when(subscriptionService.getSubscriptionUri(any())).thenCallRealMethod();

        final PostSubscriptionController controller = new PostSubscriptionController(featureToggleService,
                subscriptionService);

        mockMvc = standaloneSetup(controller)
                .setMessageConverters(new StringHttpMessageConverter(), TestUtils.JACKSON_2_HTTP_MESSAGE_CONVERTER)
                .setControllerAdvice(new PostSubscriptionExceptionHandler(), new NakadiProblemExceptionHandler())
                .setCustomArgumentResolvers(new TestHandlerMethodArgumentResolver())
                .build();
    }
 
Example 13
Source Project: servicecomb-java-chassis   Source File: GateRestTemplate.java    License: Apache License 2.0 5 votes vote down vote up
public GateRestTemplate init() {
  urlPrefix = getUrlPrefix(gateName, ITJUnitUtils.getProducerName(), schemaId);

  setUriTemplateHandler(new ITUriTemplateHandler(urlPrefix));

  setMessageConverters(Arrays.asList(
      new MappingJackson2HttpMessageConverter(),
      new StringHttpMessageConverter()
  ));

  return this;
}
 
Example 14
public ExceptionHandlerExceptionResolver() {
	StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
	stringHttpMessageConverter.setWriteAcceptCharset(false); // See SPR-7316

	this.messageConverters = new ArrayList<HttpMessageConverter<?>>();
	this.messageConverters.add(new ByteArrayHttpMessageConverter());
	this.messageConverters.add(stringHttpMessageConverter);
	this.messageConverters.add(new SourceHttpMessageConverter<Source>());
	this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());
}
 
Example 15
Source Project: SENS   Source File: DefaultAuthServiceImpl.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static RestTemplate getRestTemplate() {// 手动添加
    SimpleClientHttpRequestFactory requestFactory=new SimpleClientHttpRequestFactory();
    requestFactory.setReadTimeout(120000);
    List<HttpMessageConverter<?>> messageConverters = new LinkedList<>();
    messageConverters.add(new ByteArrayHttpMessageConverter());
    messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
    messageConverters.add(new ResourceHttpMessageConverter());
    messageConverters.add(new SourceHttpMessageConverter<Source>());
    messageConverters.add(new AllEncompassingFormHttpMessageConverter());
    messageConverters.add(new MappingJackson2HttpMessageConverter());
    RestTemplate restTemplate=new RestTemplate(messageConverters);
    restTemplate.setRequestFactory(requestFactory);
    return restTemplate;
}
 
Example 16
private void wrapConcurrentResult_ResponseBody(Object handler) throws Exception {
	List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
	converters.add(new StringHttpMessageConverter());
	this.returnValueHandlers.addHandler(new RequestResponseBodyMethodProcessor(converters));
	ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(handler, "handle");
	handlerMethod = handlerMethod.wrapConcurrentResult("bar");
	handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer);

	assertEquals("bar", this.response.getContentAsString());
}
 
Example 17
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;
}
 
Example 18
Source Project: onetwo   Source File: FormHttpMessageConverter.java    License: Apache License 2.0 5 votes vote down vote up
public FormHttpMessageConverter() {
	this.supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
	this.supportedMediaTypes.add(MediaType.MULTIPART_FORM_DATA);

	StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
	stringHttpMessageConverter.setWriteAcceptCharset(false);  // see SPR-7316

	this.partConverters.add(new ByteArrayHttpMessageConverter());
	this.partConverters.add(stringHttpMessageConverter);
	this.partConverters.add(new ResourceHttpMessageConverter());

	applyDefaultCharset();
}
 
Example 19
Source Project: FastBootWeixin   Source File: WxStringResponseBodyAdvice.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean supports(MethodParameter returnType,
                        Class<? extends HttpMessageConverter<?>> converterType) {
    return StringHttpMessageConverter.class.isAssignableFrom(converterType) &&
            CharSequence.class.isAssignableFrom(returnType.getParameterType()) &&
            returnType.hasMethodAnnotation(WxMapping.class);
}
 
Example 20
@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 21
@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);
}
 
Example 22
Source Project: paascloud-master   Source File: WeixinOAuth2Template.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 微信返回的contentType是html/text,添加相应的HttpMessageConverter来处理。
 *
 * @return the rest template
 */
@Override
protected RestTemplate createRestTemplate() {
	RestTemplate restTemplate = super.createRestTemplate();
	restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
	return restTemplate;
}
 
Example 23
@Test  // SPR-12778
public void resolveArgumentRequiredNoContentDefaultValue() throws Exception {
	this.servletRequest.setContent(new byte[0]);
	this.servletRequest.setContentType("text/plain");
	List<HttpMessageConverter<?>> converters = Collections.singletonList(new StringHttpMessageConverter());
	List<Object> advice = Collections.singletonList(new EmptyRequestBodyAdvice());
	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters, advice);
	String arg = (String) processor.resolveArgument(paramString, container, request, factory);
	assertNotNull(arg);
	assertEquals("default value for empty body", arg);
}
 
Example 24
@Test  // SPR-9160
public void handleReturnValueSortByQuality() throws Exception {
	this.servletRequest.addHeader("Accept", "text/plain; q=0.5, application/json");

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

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

	assertEquals("application/json;charset=UTF-8", servletResponse.getHeader("Content-Type"));
}
 
Example 25
@Test  // SPR-9160
public void handleReturnValueSortByQuality() throws Exception {
	this.servletRequest.addHeader("Accept", "text/plain; q=0.5, application/json");

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

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

	assertEquals("application/json;charset=UTF-8", servletResponse.getHeader("Content-Type"));
}
 
Example 26
@Test
public void supportsReturnTypeResponseBodyOnType() throws Exception {
	Method method = ResponseBodyController.class.getMethod("handle");
	MethodParameter returnType = new MethodParameter(method, -1);

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

	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);

	assertTrue("Failed to recognize type-level @ResponseBody", processor.supportsReturnType(returnType));
}
 
Example 27
@Test
public void supportsReturnTypeRestController() throws Exception {
	Method method = TestRestController.class.getMethod("handle");
	MethodParameter returnType = new MethodParameter(method, -1);

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

	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);

	assertTrue("Failed to recognize type-level @RestController", processor.supportsReturnType(returnType));
}
 
Example 28
public AnnotationMethodHandlerAdapter() {
	// no restriction of HTTP methods by default
	super(false);

	// See SPR-7316
	StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
	stringHttpMessageConverter.setWriteAcceptCharset(false);
	this.messageConverters = new HttpMessageConverter<?>[] {
		new ByteArrayHttpMessageConverter(), stringHttpMessageConverter,
		new SourceHttpMessageConverter<Source>(),
		new org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter() };
}
 
Example 29
/**
 * 实例化RestTemplate
 *
 * @return restTemplate
 */
@Bean
public RestTemplate outRestTemplate() {
    StringHttpMessageConverter m = new StringHttpMessageConverter(Charset.forName("UTF-8"));
    RestTemplate restTemplate = new RestTemplateBuilder().additionalMessageConverters(m).build(RestTemplate.class);
    return restTemplate;
}
 
Example 30
Source Project: nakadi   Source File: CursorsControllerTest.java    License: MIT License 5 votes vote down vote up
public CursorsControllerTest() throws Exception {

        subscriptionRepository = mock(SubscriptionDbRepository.class);
        authorizationService = mock(AuthorizationService.class);
        when(authorizationService.getSubject()).thenReturn(Optional.empty());
        cursorConverter = mock(CursorConverter.class);

        IntStream.range(0, DUMMY_CURSORS.size()).forEach(idx ->
                when(cursorConverter.convert(eq(DUMMY_NAKADI_CURSORS.get(idx)), any()))
                        .thenReturn(DUMMY_CURSORS.get(idx)));

        final EventTypeCache eventTypeCache = mock(EventTypeCache.class);
        doReturn(TestUtils.buildDefaultEventType()).when(eventTypeCache).getEventType(any());
        doReturn(RandomSubscriptionBuilder.builder().build()).when(subscriptionRepository).getSubscription(any());
        final CursorTokenService tokenService = mock(CursorTokenService.class);
        when(tokenService.generateToken()).thenReturn(TOKEN);

        client = mock(Client.class);

        eventStreamChecks = mock(EventStreamChecks.class);

        final CursorsController controller = new CursorsController(cursorsService, cursorConverter, tokenService,
                eventStreamChecks);

        final SecuritySettings settings = mock(SecuritySettings.class);
        doReturn(SecuritySettings.AuthMode.OFF).when(settings).getAuthMode();
        doReturn("org/zalando/nakadi").when(settings).getAdminClientId();

        mockMvc = standaloneSetup(controller)
                .setMessageConverters(new StringHttpMessageConverter(), TestUtils.JACKSON_2_HTTP_MESSAGE_CONVERTER)
                .setCustomArgumentResolvers(new ClientResolver(settings, authorizationService))
                .setControllerAdvice(new NakadiProblemExceptionHandler(), new CursorsExceptionHandler())
                .build();
    }