Java 类org.springframework.http.converter.StringHttpMessageConverter 实例源码

项目:class-guard    文件:WebMvcConfigurationSupport.java   
/**
 * Adds a set of default HttpMessageConverter instances to the given list.
 * Subclasses can call this method from {@link #configureMessageConverters(List)}.
 * @param messageConverters the list to add the default message converters to
 */
protected final void addDefaultHttpMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
    StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
    stringConverter.setWriteAcceptCharset(false);

    messageConverters.add(new ByteArrayHttpMessageConverter());
    messageConverters.add(stringConverter);
    messageConverters.add(new ResourceHttpMessageConverter());
    messageConverters.add(new SourceHttpMessageConverter<Source>());
    messageConverters.add(new AllEncompassingFormHttpMessageConverter());

    if (romePresent) {
        messageConverters.add(new AtomFeedHttpMessageConverter());
        messageConverters.add(new RssChannelHttpMessageConverter());
    }
    if (jaxb2Present) {
        messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
    }
    if (jackson2Present) {
        messageConverters.add(new MappingJackson2HttpMessageConverter());
    }
    else if (jacksonPresent) {
        messageConverters.add(new MappingJacksonHttpMessageConverter());
    }
}
项目:users-service    文件:EmailServiceImpl.java   
EmailServiceImpl(Environment env,
                 TextService text) {

    this.env     = requireNonNull(env);
    this.text    = requireNonNull(text);
    this.mailgun = new RestTemplate();

    this.mailgun.setMessageConverters(asList(
        new FormHttpMessageConverter(),
        new StringHttpMessageConverter(),
        new MappingJackson2HttpMessageConverter()
    ));

    this.mailgun.getInterceptors().add(new BasicAuthorizationInterceptor(
        "api", env.getProperty("mailgun.apiKey")
    ));
}
项目:lams    文件:RestTemplate.java   
/**
 * Create a new instance of the {@link RestTemplate} using default settings.
 * Default {@link HttpMessageConverter}s are initialized.
 */
@SuppressWarnings("deprecation")
public RestTemplate() {
    this.messageConverters.add(new ByteArrayHttpMessageConverter());
    this.messageConverters.add(new StringHttpMessageConverter());
    this.messageConverters.add(new ResourceHttpMessageConverter());
    this.messageConverters.add(new SourceHttpMessageConverter<Source>());
    this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());

    if (romePresent) {
        this.messageConverters.add(new AtomFeedHttpMessageConverter());
        this.messageConverters.add(new RssChannelHttpMessageConverter());
    }
    if (jaxb2Present) {
        this.messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
    }
    if (jackson2Present) {
        this.messageConverters.add(new MappingJackson2HttpMessageConverter());
    }
    else if (jacksonPresent) {
        this.messageConverters.add(new org.springframework.http.converter.json.MappingJacksonHttpMessageConverter());
    }
}
项目:spring-rest-basis    文件:AbstractZg2proRestTemplate.java   
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));
    */
}
项目:oma-riista-web    文件:WebMVCConfig.java   
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
    final MappingJackson2HttpMessageConverter jsonMessageConverter = jacksonMessageConverter();

    final StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
    stringHttpMessageConverter.setWriteAcceptCharset(false);

    messageConverters.add(new CSVMessageConverter());
    messageConverters.add(new ByteArrayHttpMessageConverter());
    messageConverters.add(stringHttpMessageConverter);
    messageConverters.add(new ResourceHttpMessageConverter());
    messageConverters.add(new SourceHttpMessageConverter<>());
    messageConverters.add(new AllEncompassingFormHttpMessageConverter());
    messageConverters.add(jsonMessageConverter);
    messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
}
项目:spring4-understanding    文件:ResponseBodyEmitterReturnValueHandlerTests.java   
@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);
}
项目:spring4-understanding    文件:RequestResponseBodyMethodProcessorTests.java   
@Test
public void resolveArgumentClassString() throws Exception {
    String content = "foobarbaz";
    this.servletRequest.setContent(content.getBytes("UTF-8"));
    this.servletRequest.setContentType("application/json");

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

    String result = (String) processor.resolveArgument(
            paramString, mavContainer, webRequest, binderFactory);

    assertNotNull(result);
    assertEquals("foobarbaz", result);
}
项目:spring4-understanding    文件:ServletAnnotationControllerHandlerMethodTests.java   
@Test
public void responseBodyNoAcceptableMediaType() throws ServletException, IOException {
    initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
        @Override
        public void initialize(GenericWebApplicationContext wac) {
            RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
            StringHttpMessageConverter converter = new StringHttpMessageConverter();
            adapterDef.getPropertyValues().add("messageConverters", converter);
            wac.registerBeanDefinition("handlerAdapter", adapterDef);
        }
    }, RequestResponseBodyProducesController.class);

    MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something");
    String requestBody = "Hello World";
    request.setContent(requestBody.getBytes("UTF-8"));
    request.addHeader("Content-Type", "text/plain; charset=utf-8");
    request.addHeader("Accept", "application/pdf, application/msword");
    MockHttpServletResponse response = new MockHttpServletResponse();
    getServlet().service(request, response);
    assertEquals(406, response.getStatus());
}
项目:spring4-understanding    文件:ServletAnnotationControllerHandlerMethodTests.java   
@Test
public void overlappingMessageConvertersRequestBody() throws ServletException, IOException {
    initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
        @Override
        public void initialize(GenericWebApplicationContext wac) {
            RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
            List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
            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", response.getHeader("Content-Type"));
}
项目:webapp    文件:MarkupValidationHelper.java   
/**
 * Verifies that the HTML is well formed.
 * 
 * @param markup The HTML markup to be tested.
 */
public static void verifyNoMarkupError(String markup) {
//        List<MediaType> supportedMediaTypes = new ArrayList<>();
        List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
        supportedMediaTypes.add(new MediaType("text", "html", Charset.forName("UTF-8")));

        StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
        stringHttpMessageConverter.setSupportedMediaTypes(supportedMediaTypes);       

//        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
        messageConverters.add(stringHttpMessageConverter);

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setMessageConverters(messageConverters);

        String result = restTemplate.postForObject(URL, markup, String.class);
        System.out.println("result: " + result);

        assertTrue("The document is not valid HTML5: " + markup, result.contains("The document is valid HTML5"));
}
项目:findlunch    文件:AuthenticatedRequest.java   
/**
 * Instantiates a new Authenticated request.
 *
 * @param requestReason         the request reason
 * @param context               the context
 * @param loadingMessage        the loading message
 * @param connectionInformation the connection information
 * @param userName              the user name
 * @param password              the password
 */
public AuthenticatedRequest(RequestReason requestReason, OnHttpRequestFinishedCallback context,
                            String loadingMessage, ConnectionInformation connectionInformation,
                            String userName, String password) {
    super(requestReason, context, loadingMessage, connectionInformation);
    this.userName = userName;
    this.password = password;

    // Set the username and password for creating a Basic Auth request
    authHeader = new HttpBasicAuthentication(userName, password);
    requestHeaders = new HttpHeaders();
    requestHeaders.setAuthorization(authHeader);
    requestEntity = new HttpEntity<Object>(requestHeaders);

    // Add the String message converter
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
}
项目:put-it-to-rest    文件:RestClientPostProcessor.java   
private String registerHttpMessageConverters(final String id) {
    return registry.register(id, HttpMessageConverters.class, () -> {
        final List<Object> list = list();

        LOG.debug("Client [{}]: Registering StringHttpMessageConverter", id);
        list.add(genericBeanDefinition(StringHttpMessageConverter.class)
                .addPropertyValue("writeAcceptCharset", false)
                .getBeanDefinition());

        final String objectMapperId = findObjectMapper(id);

        LOG.debug("Client [{}]: Registering MappingJackson2HttpMessageConverter referencing [{}]", id, objectMapperId);
        list.add(genericBeanDefinition(MappingJackson2HttpMessageConverter.class)
                .addConstructorArgReference(objectMapperId)
                .getBeanDefinition());

        LOG.debug("Client [{}]: Registering StreamConverter referencing [{}]", id, objectMapperId);
        list.add(genericBeanDefinition(Streams.class)
                .setFactoryMethod("streamConverter")
                .addConstructorArgReference(objectMapperId)
                .getBeanDefinition());

        return BeanDefinitionBuilder.genericBeanDefinition(ClientHttpMessageConverters.class)
                .addConstructorArgValue(list);
    });
}
项目:thingsboard    文件:AbstractControllerTest.java   
@Autowired
void setConverters(HttpMessageConverter<?>[] converters) {

    this.mappingJackson2HttpMessageConverter = Arrays.stream(converters)
            .filter(hmc -> hmc instanceof MappingJackson2HttpMessageConverter)
            .findAny()
            .get();

    this.stringHttpMessageConverter = Arrays.stream(converters)
            .filter(hmc -> hmc instanceof StringHttpMessageConverter)
            .findAny()
            .get();

    Assert.assertNotNull("the JSON message converter must not be null",
            this.mappingJackson2HttpMessageConverter);
}
项目:SpringMVCWithJavaConfig    文件:WebConfig.java   
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    ByteArrayHttpMessageConverter byteArrayHttpMessageConverter = new ByteArrayHttpMessageConverter();

    StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
    stringHttpMessageConverter.setDefaultCharset(Charset.forName("UTF-8"));
    stringHttpMessageConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL));
    //避免IE执行AJAX时,返回JSON出现下载文件
    MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
    mappingJackson2HttpMessageConverter.setDefaultCharset(Charset.forName("UTF-8"));
    mappingJackson2HttpMessageConverter.setSupportedMediaTypes(asList(MediaType.APPLICATION_JSON, MediaType.TEXT_HTML));

    converters.add(byteArrayHttpMessageConverter);
    converters.add(stringHttpMessageConverter);
    converters.add(mappingJackson2HttpMessageConverter);
}
项目:contestparser    文件:HttpMessageConvertersTests.java   
@Test
public void containsDefaults() throws Exception {
    HttpMessageConverters converters = new HttpMessageConverters();
    List<Class<?>> converterClasses = new ArrayList<Class<?>>();
    for (HttpMessageConverter<?> converter : converters) {
        converterClasses.add(converter.getClass());
    }
    assertThat(converterClasses,
            equalTo(Arrays.<Class<?>>asList(ByteArrayHttpMessageConverter.class,
                    StringHttpMessageConverter.class,
                    ResourceHttpMessageConverter.class,
                    SourceHttpMessageConverter.class,
                    AllEncompassingFormHttpMessageConverter.class,
                    MappingJackson2HttpMessageConverter.class,
                    MappingJackson2XmlHttpMessageConverter.class)));
}
项目:myfeed    文件:MyfeedAutoConfig.java   
private List<HttpMessageConverter<?>> getHttpMessageConverters() {
    List<HttpMessageConverter<?>> converters = new ArrayList<>();
    converters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new Jackson2HalModule());
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();

    converter.setObjectMapper(mapper);
    converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));

    converters.add(converter);
    return converters;
}
项目:metadatamanagement    文件:SearchResource.java   
/**
 * Create the search proxy with the given elasticsearch host url.
 *
 * @param elasticSearchConnectionUrl the elasticsearch host url
 */
@Autowired
@SuppressFBWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON")
public SearchResource(String elasticSearchConnectionUrl)
    throws UnsupportedEncodingException, MalformedURLException {
  this.connectionUrl = elasticSearchConnectionUrl;
  URL url = new URL(elasticSearchConnectionUrl);
  restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
  restTemplate.getMessageConverters()
    .add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
  String credentials = url.getUserInfo();
  if (!StringUtils.isEmpty(credentials)) {
    byte[] plainCredsBytes = credentials.getBytes("UTF-8");
    byte[] base64CredsBytes = Base64.encode(plainCredsBytes);
    base64Credentials = new String(base64CredsBytes, "UTF-8");
  }
  // prevent throwing exception on error codes
  restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
    protected boolean hasError(HttpStatus statusCode) {
        return false;
    }
  });
}
项目:nakadi    文件:EventPublishingControllerTest.java   
@Before
public void setUp() throws Exception {
    metricRegistry = new MetricRegistry();
    publisher = mock(EventPublisher.class);
    eventTypeMetricRegistry = new EventTypeMetricRegistry(metricRegistry);
    kpiPublisher = mock(NakadiKpiPublisher.class);
    settings = mock(SecuritySettings.class);
    when(settings.getAuthMode()).thenReturn(OFF);
    when(settings.getAdminClientId()).thenReturn("nakadi");

    blacklistService = Mockito.mock(BlacklistService.class);
    when(blacklistService.isProductionBlocked(any(), any())).thenReturn(false);

    final FeatureToggleService featureToggleService = Mockito.mock(FeatureToggleService.class);

    final EventPublishingController controller =
            new EventPublishingController(publisher, eventTypeMetricRegistry, blacklistService, kpiPublisher,
                    "kpiEventTypeName");

    mockMvc = standaloneSetup(controller)
            .setMessageConverters(new StringHttpMessageConverter(), TestUtils.JACKSON_2_HTTP_MESSAGE_CONVERTER)
            .setCustomArgumentResolvers(new ClientResolver(settings, featureToggleService))
            .build();
}
项目:nakadi    文件:PostSubscriptionControllerTest.java   
public PostSubscriptionControllerTest() throws Exception {

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

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

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

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

        mockMvcBuilder = standaloneSetup(controller)
                .setMessageConverters(new StringHttpMessageConverter(), TestUtils.JACKSON_2_HTTP_MESSAGE_CONVERTER)
                .setControllerAdvice(new ExceptionHandling())
                .setCustomArgumentResolvers(new TestHandlerMethodArgumentResolver());
    }
项目:orchidae    文件:_PictureController.java   
@Before
public void setup() {
    controller = new PictureController();
    controller.userUtil = userUtil;
    controller.factory = factory;
    controller.fileUtil = fileUtil;
    controller.latestPictureLimit = 10;
    controller.hookHandler = hookHandler;

    mvc = MockMvcBuilders.standaloneSetup(controller).setMessageConverters(new EntityConverter(factory),
            new StringHttpMessageConverter(), new ResourceHttpMessageConverter()).build();

    setAuthentication(owner);

    // TODO this information should be pulled out from somewhere else
    factory.create(User.class).setUsername(ownr).setPassword("1").setMemberSince(DateTime.now()).setPictureCount(
            new AtomicInteger(0)).save();

    session = new MockHttpSession();
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            SecurityContextHolder.getContext());
}
项目:class-guard    文件:RequestResponseBodyMethodProcessorTests.java   
@Test
public void resolveArgumentClassString() throws Exception {
    String content = "foobarbaz";
    this.servletRequest.setContent(content.getBytes("UTF-8"));
    this.servletRequest.setContentType("application/json");

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

    String result = (String) processor.resolveArgument(
            paramString, mavContainer, webRequest, binderFactory);

    assertNotNull(result);
    assertEquals("foobarbaz", result);
}
项目:class-guard    文件:ServletAnnotationControllerHandlerMethodTests.java   
@Test
public void responseBodyNoAcceptableMediaType() throws ServletException, IOException {
    initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
        @Override
        public void initialize(GenericWebApplicationContext wac) {
            RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
            StringHttpMessageConverter converter = new StringHttpMessageConverter();
            adapterDef.getPropertyValues().add("messageConverters", converter);
            wac.registerBeanDefinition("handlerAdapter", adapterDef);
        }
    }, RequestResponseBodyProducesController.class);

    MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something");
    String requestBody = "Hello World";
    request.setContent(requestBody.getBytes("UTF-8"));
    request.addHeader("Content-Type", "text/plain; charset=utf-8");
    request.addHeader("Accept", "application/pdf, application/msword");
    MockHttpServletResponse response = new MockHttpServletResponse();
    getServlet().service(request, response);
    assertEquals(406, response.getStatus());
}
项目:class-guard    文件:ServletAnnotationControllerHandlerMethodTests.java   
@Test
public void overlappingMessageConvertersRequestBody() throws ServletException, IOException {
    initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
        @Override
        public void initialize(GenericWebApplicationContext wac) {
            RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
            List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
            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", response.getHeader("Content-Type"));
}
项目:cats    文件:RestTemplateProducer.java   
public RestTemplate getRestTemplate()
{
    if ( null == restTemplate )
    {
        restTemplate = new RestTemplate();

        List< HttpMessageConverter< ? >> messageConverters = new ArrayList< HttpMessageConverter< ? > >();

        messageConverters.add( new JaxbSerializedHttpMessageConverter< Domain >() );
        messageConverters.add( new JaxbListHttpMessageConverter() );
        messageConverters.add( new StringHttpMessageConverter() );

        restTemplate.setMessageConverters( messageConverters );
    }
    return restTemplate;
}
项目:intermine-android    文件:RoboSpiceService.java   
@Override
public RestTemplate createRestTemplate() {
    RestTemplate rtp = new RestTemplate();
    Charset utf8 = Charset.forName(CHARSET);

    ByteArrayHttpMessageConverter byteConv = new ByteArrayHttpMessageConverter();
    StringHttpMessageConverter stringConv = new StringHttpMessageConverter(utf8);

    FormHttpMessageConverter formConv = new FormHttpMessageConverter();
    formConv.setCharset(utf8);

    List<HttpMessageConverter<?>> converters = rtp.getMessageConverters();

    converters.add(byteConv);
    converters.add(stringConv);
    converters.add(formConv);

    rtp.setMessageConverters(converters);
    return rtp;
}
项目:spring-cloud-netflix    文件:ZuulProxyTestBase.java   
@SuppressWarnings("deprecation")
@Test
public void javascriptEncodedFormParams() {
    TestRestTemplate testRestTemplate = new TestRestTemplate();
    ArrayList<HttpMessageConverter<?>> converters = new ArrayList<>();
    converters.addAll(Arrays.asList(new StringHttpMessageConverter(),
            new NoEncodingFormHttpMessageConverter()));
    testRestTemplate.getRestTemplate().setMessageConverters(converters);

    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.add("foo", "(bar)");
    ResponseEntity<String> result = testRestTemplate.postForEntity(
            "http://localhost:" + this.port + "/simple/local", map, String.class);
    assertEquals(HttpStatus.OK, result.getStatusCode());
    assertEquals("Posted [(bar)] and Content-Length was: 13!", result.getBody());
}
项目:spring-cloud-netflix    文件:RestClientRibbonCommandIntegrationTests.java   
@Override
@SuppressWarnings("deprecation")
@Test
public void javascriptEncodedFormParams() {
    TestRestTemplate testRestTemplate = new TestRestTemplate();
    ArrayList<HttpMessageConverter<?>> converters = new ArrayList<>();
    converters.addAll(Arrays.asList(new StringHttpMessageConverter(),
            new NoEncodingFormHttpMessageConverter()));
    testRestTemplate.getRestTemplate().setMessageConverters(converters);

    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.add("foo", "(bar)");
    ResponseEntity<String> result = testRestTemplate.postForEntity(
            "http://localhost:" + this.port + "/simple/local", map, String.class);
    assertEquals(HttpStatus.OK, result.getStatusCode());
    assertEquals("Posted [(bar)] and Content-Length was: -1!", result.getBody());
}
项目:lodms-plugins    文件:WkdSpotlightNifTagger.java   
private String getTagsForText(URI fragment,String text) throws TransformException {
    RestTemplate rest = new RestTemplate();
    CommonsClientHttpRequestFactory clientHttpRequestFactory = new CommonsClientHttpRequestFactory();
    clientHttpRequestFactory.setReadTimeout(10000);
    rest.setRequestFactory(clientHttpRequestFactory);
    List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
    converters.add(new FormHttpMessageConverter());
    converters.add(new StringHttpMessageConverter());
    rest.setMessageConverters(converters);
    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    map.add("prefix", fragment.stringValue()+"#");
    map.add("text", text);
    HttpEntity<?> httpEntity = new HttpEntity<Object>(map, getHttpHeaders());
    try {
        String annotation = rest.postForObject(config.getSpotlightUrl(), httpEntity, String.class);
        return annotation;
    }
    catch (RestClientException e) {
        throw new TransformException(e.getMessage(),e);
    }

}
项目:xm-uaa    文件:TwitterEscapingFormHttpMessageConverter.java   
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);
}
项目:xm-uaa    文件:TemplateUtil.java   
public static RestTemplate getTemplate(ClientHttpRequestInterceptor interceptor) {
    RestTemplate restTemplate = new RestTemplate();

    List<ClientHttpRequestInterceptor> ris = new ArrayList<>();
    ris.add(interceptor);
    restTemplate.setInterceptors(ris);
    SimpleClientHttpRequestFactory httpFactory = new SimpleClientHttpRequestFactory();
    httpFactory.setOutputStreaming(false);
    restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(httpFactory));
    restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
    return restTemplate;
}
项目:cf-java-client-sap    文件:RestUtil.java   
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;
}
项目:cf-java-client-sap    文件:RestUtil.java   
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;
}
项目:csap-core    文件:CsapCoreService.java   
@Bean ( name = "csapEventsService" )
public RestTemplate csapEventsService ( CsapRestTemplateFactory factory ) {

    RestTemplate restTemplate = factory.buildDefaultTemplate( "csapEvents", false, 10, 10, 5, 5, 300 );

    restTemplate.getMessageConverters().clear();
    restTemplate.getMessageConverters().add( new FormHttpMessageConverter() );
    restTemplate.getMessageConverters().add( new StringHttpMessageConverter() );
    restTemplate.getMessageConverters().add( new MappingJackson2HttpMessageConverter() );

    return restTemplate;
}
项目:sns-todo    文件:QQOAuth2RestTemplate.java   
public QQOAuth2RestTemplate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext context) {
    super(resource, context);
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
    messageConverters.add(new StringHttpMessageConverter());//for https://graph.qq.com/oauth2.0/me
    messageConverters.add(new QQTokenHttpMessageConverter()); //for  token
    messageConverters.add(new MappingJackson2HttpMessageConverter() {
        @Override
        protected boolean canRead(MediaType mediaType) {
            return true;
        }
    });//for userInfo need custom

    this.setMessageConverters(messageConverters);
    this.setAccessTokenProvider(new QQAuthorizationCodeAccessTokenProvider(messageConverters));
}
项目:sns-todo    文件:WebMvcConfig.java   
@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());
}
项目:crnk-framework    文件:SpringParameterProvider.java   
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;
}
项目:omero-ms-queue    文件:WebWiring.java   
private void setStringConverterMediaTypes(HttpMessageConverter<?> x) {
    StringHttpMessageConverter converter = (StringHttpMessageConverter) x;
    List<MediaType> mediaTypes = Arrays.asList(
            new MediaType("text", "plain", StandardCharsets.UTF_8), 
            MediaType.ALL);
    converter.setSupportedMediaTypes(mediaTypes);
}
项目:xm-ms-entity    文件:MultipartMixedConverter.java   
public MultipartMixedConverter() {
    this.supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
    this.supportedMediaTypes.add(MediaType.MULTIPART_FORM_DATA);
    this.supportedMediaTypes.add(mixed);
    this.supportedMediaTypes.add(related);

    this.partConverters.add(new ByteArrayHttpMessageConverter());
    StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
    stringHttpMessageConverter.setWriteAcceptCharset(false);
    this.partConverters.add(stringHttpMessageConverter);
    this.partConverters.add(new ResourceHttpMessageConverter());
    this.partConverters.add(new MappingJackson2HttpMessageConverter());
}
项目:xm-ms-entity    文件:TemplateUtil.java   
public static RestTemplate getTemplate(ClientHttpRequestInterceptor interceptor) {
    RestTemplate restTemplate = new RestTemplate();

    List<ClientHttpRequestInterceptor> ris = new ArrayList<>();
    ris.add(interceptor);
    restTemplate.setInterceptors(ris);
    SimpleClientHttpRequestFactory httpFactory = new SimpleClientHttpRequestFactory();
    httpFactory.setOutputStreaming(false);
    restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(httpFactory));
    restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
    return restTemplate;
}
项目:ServiceServer    文件:SmsService.java   
/**
 * Initialize a {@code SmsService} instance.
 *
 * @param id The LC id
 * @param key The LC key
 */
public void init(String id, String key) {
    StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
    converter.setWriteAcceptCharset(false);
    restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(0, converter);
    mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    headers = new HttpHeaders();
    headers.add("X-LC-Id", id);
    headers.add("X-LC-Key", key);
    headers.setContentType(MediaType.APPLICATION_JSON);
}