org.springframework.http.converter.ByteArrayHttpMessageConverter源码实例Demo

类org.springframework.http.converter.ByteArrayHttpMessageConverter源码实例Demo

下面列出了org.springframework.http.converter.ByteArrayHttpMessageConverter 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

/**
 * 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;
}
 
@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());
}
 
@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));
}
 
@Test
public void unsupportedRequestBody() throws Exception {
	initServlet(wac -> {
		RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
		adapterDef.getPropertyValues().add("messageConverters", new ByteArrayHttpMessageConverter());
		wac.registerBeanDefinition("handlerAdapter", adapterDef);
	}, RequestResponseBodyController.class);

	MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something");
	String requestBody = "Hello World";
	request.setContent(requestBody.getBytes("UTF-8"));
	request.addHeader("Content-Type", "application/pdf");
	MockHttpServletResponse response = new MockHttpServletResponse();
	getServlet().service(request, response);
	assertEquals(415, response.getStatus());
	assertNotNull("No Accept response header set", response.getHeader("Accept"));
}
 
@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());
}
 
@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));
}
 
@Test
public void unsupportedRequestBody() throws Exception {
	initServlet(wac -> {
		RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
		adapterDef.getPropertyValues().add("messageConverters", new ByteArrayHttpMessageConverter());
		wac.registerBeanDefinition("handlerAdapter", adapterDef);
	}, RequestResponseBodyController.class);

	MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something");
	String requestBody = "Hello World";
	request.setContent(requestBody.getBytes("UTF-8"));
	request.addHeader("Content-Type", "application/pdf");
	MockHttpServletResponse response = new MockHttpServletResponse();
	getServlet().service(request, response);
	assertEquals(415, response.getStatus());
	assertNotNull("No Accept response header set", response.getHeader("Accept"));
}
 
源代码8 项目: spring-boot-chatbot   文件: RestTemplateFactory.java
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;
}
 
@Test
public void unsupportedRequestBody() throws ServletException, IOException {
	@SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() {
		@Override
		protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
			GenericWebApplicationContext wac = new GenericWebApplicationContext();
			wac.registerBeanDefinition("controller", new RootBeanDefinition(RequestResponseBodyController.class));
			RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class);
			adapterDef.getPropertyValues().add("messageConverters", new ByteArrayHttpMessageConverter());
			wac.registerBeanDefinition("handlerAdapter", adapterDef);
			wac.refresh();
			return wac;
		}
	};
	servlet.init(new MockServletConfig());

	MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something");
	String requestBody = "Hello World";
	request.setContent(requestBody.getBytes("UTF-8"));
	request.addHeader("Content-Type", "application/pdf");
	MockHttpServletResponse response = new MockHttpServletResponse();
	servlet.service(request, response);
	assertEquals(415, response.getStatus());
	assertNotNull("No Accept response header set", response.getHeader("Accept"));
}
 
@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));
}
 
@Test
public void unsupportedRequestBody() throws ServletException, IOException {
	initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
		@Override
		public void initialize(GenericWebApplicationContext wac) {
			RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
			adapterDef.getPropertyValues().add("messageConverters", new ByteArrayHttpMessageConverter());
			wac.registerBeanDefinition("handlerAdapter", adapterDef);
		}
	}, RequestResponseBodyController.class);

	MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something");
	String requestBody = "Hello World";
	request.setContent(requestBody.getBytes("UTF-8"));
	request.addHeader("Content-Type", "application/pdf");
	MockHttpServletResponse response = new MockHttpServletResponse();
	getServlet().service(request, response);
	assertEquals(415, response.getStatus());
	assertNotNull("No Accept response header set", response.getHeader("Accept"));
}
 
@Bean
@ConditionalOnMissingBean
public ProxyExchangeArgumentResolver proxyExchangeArgumentResolver(
		Optional<RestTemplateBuilder> optional, ProxyProperties proxy) {
	RestTemplateBuilder builder = optional.orElse(new RestTemplateBuilder());
	RestTemplate template = builder.build();
	template.setErrorHandler(new NoOpResponseErrorHandler());
	template.getMessageConverters().add(new ByteArrayHttpMessageConverter() {
		@Override
		public boolean supports(Class<?> clazz) {
			return true;
		}
	});
	ProxyExchangeArgumentResolver resolver = new ProxyExchangeArgumentResolver(
			template);
	resolver.setHeaders(proxy.convertHeaders());
	resolver.setAutoForwardedHeaders(proxy.getAutoForward());
	resolver.setSensitive(proxy.getSensitive()); // can be null
	return resolver;
}
 
源代码13 项目: openvsx   文件: RegistryApplication.java
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
	return builder
           .messageConverters(
               new ByteArrayHttpMessageConverter(),
               new StringHttpMessageConverter(),
               new MappingJackson2HttpMessageConverter())
           .build();
}
 
源代码14 项目: SENS   文件: DefaultAuthServiceImpl.java
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;
}
 
public ExceptionHandlerExceptionResolver() {
	this.messageConverters = new ArrayList<>();
	this.messageConverters.add(new ByteArrayHttpMessageConverter());
	this.messageConverters.add(new StringHttpMessageConverter());
	try {
		this.messageConverters.add(new SourceHttpMessageConverter<>());
	}
	catch (Error err) {
		// Ignore when no TransformerFactory implementation is available
	}
	this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());
}
 
public RequestMappingHandlerAdapter() {
	this.messageConverters = new ArrayList<>(4);
	this.messageConverters.add(new ByteArrayHttpMessageConverter());
	this.messageConverters.add(new StringHttpMessageConverter());
	try {
		this.messageConverters.add(new SourceHttpMessageConverter<>());
	}
	catch (Error err) {
		// Ignore when no TransformerFactory implementation is available
	}
	this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());
}
 
@Test  // SPR-13319
public void standardMultipartResolverWithEncodedFileName() throws Exception {
	byte[] boundary = MimeTypeUtils.generateMultipartBoundary();
	String boundaryText = new String(boundary, "US-ASCII");
	Map<String, String> params = Collections.singletonMap("boundary", boundaryText);

	String content =
			"--" + boundaryText + "\n" +
			"Content-Disposition: form-data; name=\"file\"; filename*=\"utf-8''%C3%A9l%C3%A8ve.txt\"\n" +
			"Content-Type: text/plain\n" +
			"Content-Length: 7\n" +
			"\n" +
			"content\n" +
			"--" + boundaryText + "--";

	RequestEntity<byte[]> requestEntity =
			RequestEntity.post(new URI(baseUrl + "/standard-resolver/spr13319"))
					.contentType(new MediaType(MediaType.MULTIPART_FORM_DATA, params))
					.body(content.getBytes(StandardCharsets.US_ASCII));

	ByteArrayHttpMessageConverter converter = new ByteArrayHttpMessageConverter();
	converter.setSupportedMediaTypes(Collections.singletonList(MediaType.MULTIPART_FORM_DATA));
	this.restTemplate.setMessageConverters(Collections.singletonList(converter));

	ResponseEntity<Void> responseEntity = restTemplate.exchange(requestEntity, Void.class);
	assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
}
 
@Test
public void handleReturnValueString() throws Exception {
	List<HttpMessageConverter<?>>converters = new ArrayList<>();
	converters.add(new ByteArrayHttpMessageConverter());
	converters.add(new StringHttpMessageConverter());

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

	assertEquals("text/plain;charset=ISO-8859-1", servletResponse.getHeader("Content-Type"));
	assertEquals("Foo", servletResponse.getContentAsString());
}
 
@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());
}
 
@Test
public void handleReturnValueStringAcceptCharset() throws Exception {
	this.servletRequest.addHeader("Accept", "text/plain;charset=UTF-8");

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

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

	assertEquals("text/plain;charset=UTF-8", servletResponse.getHeader("Content-Type"));
}
 
public ExceptionHandlerExceptionResolver() {
	StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
	stringHttpMessageConverter.setWriteAcceptCharset(false);  // see SPR-7316

	this.messageConverters = new ArrayList<>();
	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());
}
 
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());
}
 
@Test  // SPR-13319
public void standardMultipartResolverWithEncodedFileName() throws Exception {
	byte[] boundary = MimeTypeUtils.generateMultipartBoundary();
	String boundaryText = new String(boundary, "US-ASCII");
	Map<String, String> params = Collections.singletonMap("boundary", boundaryText);

	String content =
			"--" + boundaryText + "\n" +
			"Content-Disposition: form-data; name=\"file\"; filename*=\"utf-8''%C3%A9l%C3%A8ve.txt\"\n" +
			"Content-Type: text/plain\n" +
			"Content-Length: 7\n" +
			"\n" +
			"content\n" +
			"--" + boundaryText + "--";

	RequestEntity<byte[]> requestEntity =
			RequestEntity.post(new URI(baseUrl + "/standard-resolver/spr13319"))
					.contentType(new MediaType(MediaType.MULTIPART_FORM_DATA, params))
					.body(content.getBytes(StandardCharsets.US_ASCII));

	ByteArrayHttpMessageConverter converter = new ByteArrayHttpMessageConverter();
	converter.setSupportedMediaTypes(Collections.singletonList(MediaType.MULTIPART_FORM_DATA));
	this.restTemplate.setMessageConverters(Collections.singletonList(converter));

	ResponseEntity<Void> responseEntity = restTemplate.exchange(requestEntity, Void.class);
	assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
}
 
@Test
public void handleReturnValueString() throws Exception {
	List<HttpMessageConverter<?>>converters = new ArrayList<>();
	converters.add(new ByteArrayHttpMessageConverter());
	converters.add(new StringHttpMessageConverter());

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

	assertEquals("text/plain;charset=ISO-8859-1", servletResponse.getHeader("Content-Type"));
	assertEquals("Foo", servletResponse.getContentAsString());
}
 
@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());
}
 
@Test
public void handleReturnValueStringAcceptCharset() throws Exception {
	this.servletRequest.addHeader("Accept", "text/plain;charset=UTF-8");

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

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

	assertEquals("text/plain;charset=UTF-8", servletResponse.getHeader("Content-Type"));
}
 
@Bean(name = FILE_REST_OPERATIONS)
public RestOperations fileRestOperations() {
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setConnectTimeout(20000);
    factory.setReadTimeout(20000);
    RestTemplate restTemplate = (RestTemplate) RestTemplateFactory.getRestOperations(factory);
    restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
    return restTemplate;
}
 
源代码28 项目: cf-java-client-sap   文件: RestUtil.java
private List<HttpMessageConverter<?>> getHttpMessageConverters() {
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
    messageConverters.add(new ByteArrayHttpMessageConverter());
    messageConverters.add(new StringHttpMessageConverter());
    messageConverters.add(new ResourceHttpMessageConverter());
    messageConverters.add(new MappingJackson2HttpMessageConverter());
    return messageConverters;
}
 
@SuppressWarnings("unchecked")
@Test
public void setMessageConvertersWithUnderlying() {
  ByteArrayHttpMessageConverter messageConverter = mock(ByteArrayHttpMessageConverter.class);

  wrapper.setMessageConverters(singletonList(messageConverter));

  assertThat(wrapper.getMessageConverters(), contains(messageConverter));
  assertThat(wrapper.defaultRestTemplate.getMessageConverters(), contains(messageConverter));

  verify(underlying, never()).setMessageConverters(singletonList(messageConverter));
}
 
源代码30 项目: syndesis   文件: BaseITCase.java
@Autowired
public void setRestTemplate(TestRestTemplate testRestTemplate) {
    List<HttpMessageConverter<?>> messageConverters = testRestTemplate.getRestTemplate().getMessageConverters();
    messageConverters.add(0, new YamlJackson2HttpMessageConverter());
    messageConverters.add(0, new JsonJackson2HttpMessageConverter());
    messageConverters.add( 0, new ByteArrayHttpMessageConverter());
    this.restTemplate = testRestTemplate;
}
 
如果文章对您有帮助,请点击页面广告。以鼓励作者做出的努力。
 类所在包
 类方法
 同包方法