org.springframework.http.converter.StringHttpMessageConverter Java Examples

The following examples show how to use org.springframework.http.converter.StringHttpMessageConverter. 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: PostSubscriptionControllerTest.java    From nakadi with 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 #2
Source File: RestTemplateFactory.java    From spring-boot-chatbot with 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 #3
Source File: JpomApplication.java    From Jpom with 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 #4
Source File: WebMvcConfig.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
/**
 * 自定义消息转换器:使用 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 #5
Source File: RouterFunctionMapping.java    From spring-analysis-note with 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 #6
Source File: RestTemplateConfiguration.java    From seed with 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 #7
Source File: ResponseBodyEmitterReturnValueHandlerTests.java    From spring4-understanding with Apache License 2.0 6 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.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 File: ServletAnnotationControllerHandlerMethodTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #9
Source File: WebConfiguration.java    From java-platform with 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 #10
Source File: AnnotationDrivenBeanDefinitionParserTests.java    From java-technology-stack 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 #11
Source File: HttpEntityMethodProcessorTests.java    From java-technology-stack with MIT License 6 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 = 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 #12
Source File: ServletAnnotationControllerHandlerMethodTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #13
Source File: WeixinOAuth2Template.java    From pre with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 微信返回的contentType是html/text,添加相应的HttpMessageConverter来处理。
 */
@Override
protected RestTemplate createRestTemplate() {
    RestTemplate restTemplate = super.createRestTemplate();
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
    return restTemplate;
}
 
Example #14
Source File: WeiXinImpl.java    From pre with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 使用utf-8 替换默认的ISO-8859-1编码
 * @return
 */
@Override
protected List<HttpMessageConverter<?>> getMessageConverters() {
    List<HttpMessageConverter<?>> messageConverters = super.getMessageConverters();
    messageConverters.remove(0);
    messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
    return messageConverters;
}
 
Example #15
Source File: HeaderRequestMatchersIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setup() {
	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new StringHttpMessageConverter());
	converters.add(new MappingJackson2HttpMessageConverter());

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

	this.mockServer = MockRestServiceServer.createServer(this.restTemplate);
}
 
Example #16
Source File: CredHubRestTemplateFactory.java    From spring-credhub with Apache License 2.0 5 votes vote down vote up
/**
 * Configure a {@link RestTemplate} for communication with a CredHub server.
 * @param restTemplate an existing {@link RestTemplate} to configure
 * @param baseUri the base URI for the CredHub server
 * @param clientHttpRequestFactory the {@link ClientHttpRequestFactory} to use when
 * creating new connections
 */
private static void configureRestTemplate(RestTemplate restTemplate, String baseUri,
		ClientHttpRequestFactory clientHttpRequestFactory) {
	restTemplate.setRequestFactory(clientHttpRequestFactory);
	restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory(baseUri));
	restTemplate.getInterceptors().add(new CredHubRequestInterceptor());
	restTemplate.setMessageConverters(
			Arrays.asList(new ByteArrayHttpMessageConverter(), new StringHttpMessageConverter(),
					new MappingJackson2HttpMessageConverter(JsonUtils.buildObjectMapper())));
}
 
Example #17
Source File: ServletInvocableHandlerMethodTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void wrapConcurrentResult_ResponseEntityNullBody() throws Exception {
	List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
	converters.add(new StringHttpMessageConverter());
	List<Object> advice = Collections.singletonList(mock(ResponseBodyAdvice.class));
	HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(converters, null, advice);
	this.returnValueHandlers.addHandler(processor);
	ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new ResponseEntityHandler(), "handleDeferred");
	handlerMethod = handlerMethod.wrapConcurrentResult(new ResponseEntity<>(HttpStatus.OK));
	handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer);

	assertEquals(200, this.response.getStatus());
	assertEquals("", this.response.getContentAsString());
}
 
Example #18
Source File: FrontServiceApplicationStart.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/**
 * 实例化RestTemplate,通过@LoadBalanced注解开启均衡负载能力.
 *
 * @return restTemplate
 */
@Bean
public RestTemplate outRestTemplate() {
    StringHttpMessageConverter m = new StringHttpMessageConverter(Charset.forName("UTF-8"));
    RestTemplate restTemplate = new RestTemplateBuilder().additionalMessageConverters(m).build();
    return restTemplate;
}
 
Example #19
Source File: HttpConverterConfig.java    From encrypt-body-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    MappingJackson2HttpMessageConverter converter = mappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(new LinkedList<MediaType>(){{
        add(MediaType.TEXT_HTML);
        add(MediaType.APPLICATION_JSON_UTF8);
    }});
    converters.add(new StringHttpMessageConverter());
    converters.add(converter);
}
 
Example #20
Source File: VaultClients.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link RestTemplate} for Vault interaction. {@link RestTemplate} is
 * configured with a {@link ClientHttpRequestInterceptor} to enforce serialization to
 * a byte array prior continuing the request. Eager serialization leads to a known
 * request body size that is required to send a
 * {@link org.springframework.http.HttpHeaders#CONTENT_LENGTH} request header.
 * Otherwise, Vault will deny body processing.
 * <p>
 * Requires Jackson 2 for Object-to-JSON mapping.
 * @return the {@link RestTemplate}.
 * @see org.springframework.http.client.Netty4ClientHttpRequestFactory
 * @see MappingJackson2HttpMessageConverter
 */
public static RestTemplate createRestTemplate() {

	List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(3);
	messageConverters.add(new ByteArrayHttpMessageConverter());
	messageConverters.add(new StringHttpMessageConverter());
	messageConverters.add(new MappingJackson2HttpMessageConverter());

	RestTemplate restTemplate = new RestTemplate(messageConverters);

	restTemplate.getInterceptors().add((request, body, execution) -> execution.execute(request, body));

	return restTemplate;
}
 
Example #21
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void addContentDispositionHeader() throws Exception {
	ContentNegotiationManagerFactoryBean factory = new ContentNegotiationManagerFactoryBean();
	factory.addMediaType("pdf", new MediaType("application", "pdf"));
	factory.afterPropertiesSet();

	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(
			Collections.singletonList(new StringHttpMessageConverter()),
			factory.getObject());

	assertContentDisposition(processor, false, "/hello.json", "whitelisted extension");
	assertContentDisposition(processor, false, "/hello.pdf", "registered extension");
	assertContentDisposition(processor, true, "/hello.dataless", "unknown extension");

	// path parameters
	assertContentDisposition(processor, false, "/hello.json;a=b", "path param shouldn't cause issue");
	assertContentDisposition(processor, true, "/hello.json;a=b;setup.dataless", "unknown ext in path params");
	assertContentDisposition(processor, true, "/hello.dataless;a=b;setup.json", "unknown ext in filename");
	assertContentDisposition(processor, false, "/hello.json;a=b;setup.json", "whitelisted extensions");

	// encoded dot
	assertContentDisposition(processor, true, "/hello%2Edataless;a=b;setup.json", "encoded dot in filename");
	assertContentDisposition(processor, true, "/hello.json;a=b;setup%2Edataless", "encoded dot in path params");
	assertContentDisposition(processor, true, "/hello.dataless%3Bsetup.bat", "encoded dot in path params");

	this.servletRequest.setAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE, "/hello.bat");
	assertContentDisposition(processor, true, "/bonjour", "forwarded URL");
	this.servletRequest.removeAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE);
}
 
Example #22
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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 #23
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test(expected = HttpMessageNotReadableException.class)  // SPR-9942
public void resolveArgumentRequiredNoContent() throws Exception {
	this.servletRequest.setContent(new byte[0]);
	this.servletRequest.setContentType("text/plain");
	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new StringHttpMessageConverter());
	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);
	processor.resolveArgument(paramString, container, request, factory);
}
 
Example #24
Source File: SpringRESTClientConnector.java    From egeria with Apache License 2.0 5 votes vote down vote up
/**
 * Default constructor
 */
public SpringRESTClientConnector() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException
{
    super();

    /*
     * Rather than creating a RestTemplate directly, the RestTemplateBuilder is used so that the
     * uriTemplateHandler can be specified. The URI encoding is set to VALUES_ONLY so that the
     * '+' character, which is used in queryParameters conveying searchCriteria, which can be a
     * regex, is encoded as '+' and not converted to a space character.
     * Prior to this change a regex containing a '+' character would be split into two space
     * separated words. For example, the regex "name_0+7" (which would match name_07, name_007,
     * name_0007, etc) would be sent to the server as "name_0 7".
     */
    DefaultUriBuilderFactory builderFactory = new DefaultUriBuilderFactory();
    builderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.VALUES_ONLY);


    /* TODO: Disable SSL cert verification -- for now */
    HttpsURLConnection.setDefaultHostnameVerifier(bypassVerifier);
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, INSECURE_MANAGER, null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    restTemplate = new RestTemplate();

    restTemplate.setUriTemplateHandler(builderFactory);

    /* Ensure that the REST template always uses UTF-8 */
    List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
    converters.removeIf(httpMessageConverter -> httpMessageConverter instanceof StringHttpMessageConverter);
    converters.add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));

}
 
Example #25
Source File: RequestMappingHandlerAdapter.java    From java-technology-stack with MIT License 5 votes vote down vote up
public RequestMappingHandlerAdapter() {
	StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
	stringHttpMessageConverter.setWriteAcceptCharset(false);  // see SPR-7316

	this.messageConverters = new ArrayList<>(4);
	this.messageConverters.add(new ByteArrayHttpMessageConverter());
	this.messageConverters.add(stringHttpMessageConverter);
	try {
		this.messageConverters.add(new SourceHttpMessageConverter<>());
	}
	catch (Error err) {
		// Ignore when no TransformerFactory implementation is available
	}
	this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());
}
 
Example #26
Source File: HttpMessageConverterConfiguration.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Bean
public HttpMessageConverters messageConverters() {
  GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
  gsonHttpMessageConverter.setGson(
          new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").create());
  final List<HttpMessageConverter<?>> converters = Lists.newArrayList(
          new ByteArrayHttpMessageConverter(), new StringHttpMessageConverter(),
          new AllEncompassingFormHttpMessageConverter(), gsonHttpMessageConverter);
  return new HttpMessageConverters() {
    @Override
    public List<HttpMessageConverter<?>> getConverters() {
      return converters;
    }
  };
}
 
Example #27
Source File: AbilityService.java    From cubeai with Apache License 2.0 5 votes vote down vote up
public ResponseEntity<String> apiGateway(String url, String requestBody, MultiValueMap<String,String> requestHeader) {
    log.debug("Start API forwarding");

    try {
        HttpEntity<String> httpEntity = new HttpEntity<>(requestBody, requestHeader);
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); // 直接使用RestTemplate的POST方法时,字符串默认使用“ISO-8859-1”编码,需要转换
        ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class);
        return ResponseEntity.status(response.getStatusCodeValue()).body(response.getBody());
    } catch(HttpClientErrorException e) {
        return ResponseEntity.status(e.getStatusCode()).body(e.getResponseBodyAsString());
    }
}
 
Example #28
Source File: WechatMpOAuth2Template.java    From cola with MIT License 5 votes vote down vote up
/**
 * 微信返回的contentType是html/text,添加相应的HttpMessageConverter来处理。
 */
@Override
protected RestTemplate createRestTemplate() {
	RestTemplate restTemplate = super.createRestTemplate();
	restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
	return restTemplate;
}
 
Example #29
Source File: OneClickImporterControllerTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@BeforeEach
void before() {
  OneClickImporterController oneClickImporterController =
      new OneClickImporterController(
          menuReaderService, fileStore, oneClickImportJobExecutionFactory, jobExecutor);

  when(menuReaderService.findMenuItemPath(OneClickImporterController.ONE_CLICK_IMPORTER))
      .thenReturn("/test-path");
  when(localeResolver.resolveLocale(any())).thenReturn(new Locale("nl"));
  when(appSettings.getLanguageCode()).thenReturn("en");
  User user = mock(User.class);
  when(user.isSuperuser()).thenReturn(false);
  when(userAccountService.getCurrentUser()).thenReturn(user);

  OneClickImportJobExecution jobExecution = mock(OneClickImportJobExecution.class);
  when(oneClickImportJobExecutionFactory.create()).thenReturn(jobExecution);

  EntityType oneClickImportJobExecutionEntityType = mock(EntityType.class);
  when(jobExecution.getEntityType()).thenReturn(oneClickImportJobExecutionEntityType);
  when(jobExecution.getIdValue()).thenReturn("id_1");
  when(oneClickImportJobExecutionEntityType.getId()).thenReturn("jobExecutionId");

  StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
  stringConverter.setWriteAcceptCharset(false);

  mockMvc =
      MockMvcBuilders.standaloneSetup(oneClickImporterController)
          .setLocaleResolver(localeResolver)
          .setMessageConverters(gsonHttpMessageConverter, stringConverter)
          .build();
}
 
Example #30
Source File: WechatImpl.java    From cola with MIT License 5 votes vote down vote up
/**
 * 使用utf-8 替换默认的ISO-8859-1编码
 * @return
 */
@Override
protected List<HttpMessageConverter<?>> getMessageConverters() {
    List<HttpMessageConverter<?>> messageConverters = super.getMessageConverters();
    messageConverters.remove(0);
    messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
    return messageConverters;
}