类org.springframework.http.HttpInputMessage源码实例Demo

下面列出了怎么用org.springframework.http.HttpInputMessage的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: lams   文件: SourceHttpMessageConverter.java
@Override
@SuppressWarnings("unchecked")
protected T readInternal(Class<? extends T> clazz, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	InputStream body = inputMessage.getBody();
	if (DOMSource.class == clazz) {
		return (T) readDOMSource(body);
	}
	else if (SAXSource.class == clazz) {
		return (T) readSAXSource(body);
	}
	else if (StAXSource.class == clazz) {
		return (T) readStAXSource(body);
	}
	else if (StreamSource.class == clazz || Source.class == clazz) {
		return (T) readStreamSource(body);
	}
	else {
		throw new HttpMessageConversionException("Could not read class [" + clazz +
				"]. Only DOMSource, SAXSource, StAXSource, and StreamSource are supported.");
	}
}
 
源代码2 项目: dpCms   文件: Fastjson2HttpMessageConverter.java
@Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException,  HttpMessageNotReadableException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    InputStream in = inputMessage.getBody();
    byte[] buf = new byte[1024];
    for (;;) {
        int len = in.read(buf);
        if (len == -1) {
            break;
        }
        if (len > 0) {
            baos.write(buf, 0, len);
        }
    }
    byte[] bytes = baos.toByteArray();
    return JSON.parseObject(bytes, 0, bytes.length, charset.newDecoder(), clazz);
}
 
@Override
protected Properties readInternal(Class<? extends Properties> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    Properties properties = new Properties();
    // 获取请求头
    HttpHeaders headers = inputMessage.getHeaders();
    // 获取 content-type
    MediaType contentType = headers.getContentType();
    // 获取编码
    Charset charset = null;
    if (contentType != null) {
        charset = contentType.getCharset();
    }

    charset = charset == null ? Charset.forName("UTF-8") : charset;

    // 获取请求体
    InputStream body = inputMessage.getBody();
    InputStreamReader inputStreamReader = new InputStreamReader(body, charset);

    properties.load(inputStreamReader);
    return properties;
}
 
public EmptyBodyCheckingHttpInputMessage(HttpInputMessage inputMessage) throws IOException {
	this.headers = inputMessage.getHeaders();
	InputStream inputStream = inputMessage.getBody();
	if (inputStream == null) {
		this.body = null;
	}
	else if (inputStream.markSupported()) {
		inputStream.mark(1);
		this.body = (inputStream.read() != -1 ? inputStream : null);
		inputStream.reset();
	}
	else {
		PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream);
		int b = pushbackInputStream.read();
		if (b == -1) {
			this.body = null;
		}
		else {
			this.body = pushbackInputStream;
			pushbackInputStream.unread(b);
		}
	}
	this.method = ((HttpRequest) inputMessage).getMethod();
}
 
@Test
public void resolveArgument() throws Exception {
	MediaType contentType = MediaType.TEXT_PLAIN;
	servletRequest.addHeader("Content-Type", contentType.toString());

	String body = "Foo";
	servletRequest.setContent(body.getBytes(StandardCharsets.UTF_8));

	given(stringMessageConverter.canRead(String.class, contentType)).willReturn(true);
	given(stringMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(body);

	Object result = processor.resolveArgument(paramRequestBodyString, mavContainer,
			webRequest, new ValidatingBinderFactory());

	assertEquals("Invalid argument", body, result);
	assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled());
}
 
@Override
protected Resource readInternal(Class<? extends Resource> clazz, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	if (this.supportsReadStreaming && InputStreamResource.class == clazz) {
		return new InputStreamResource(inputMessage.getBody()) {
			@Override
			public String getFilename() {
				return inputMessage.getHeaders().getContentDisposition().getFilename();
			}
		};
	}
	else if (Resource.class == clazz || ByteArrayResource.class.isAssignableFrom(clazz)) {
		byte[] body = StreamUtils.copyToByteArray(inputMessage.getBody());
		return new ByteArrayResource(body) {
			@Override
			@Nullable
			public String getFilename() {
				return inputMessage.getHeaders().getContentDisposition().getFilename();
			}
		};
	}
	else {
		throw new HttpMessageNotReadableException("Unsupported resource class: " + clazz, inputMessage);
	}
}
 
private MultiValueMap<String, String> parseFormData(final MediaType mediaType) {
	HttpInputMessage message = new HttpInputMessage() {
		@Override
		public InputStream getBody() {
			return (content != null ? new ByteArrayInputStream(content) : StreamUtils.emptyInput());
		}
		@Override
		public HttpHeaders getHeaders() {
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(mediaType);
			return headers;
		}
	};

	try {
		return new FormHttpMessageConverter().read(null, message);
	}
	catch (IOException ex) {
		throw new IllegalStateException("Failed to parse form data in request body", ex);
	}
}
 
@Test
public void shouldResolveHttpEntityArgument() throws Exception {
	String body = "Foo";

	MediaType contentType = TEXT_PLAIN;
	servletRequest.addHeader("Content-Type", contentType.toString());
	servletRequest.setContent(body.getBytes(StandardCharsets.UTF_8));

	given(stringHttpMessageConverter.canRead(String.class, contentType)).willReturn(true);
	given(stringHttpMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(body);

	Object result = processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null);

	assertTrue(result instanceof HttpEntity);
	assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled());
	assertEquals("Invalid argument", body, ((HttpEntity<?>) result).getBody());
}
 
/**
 * Parse the body as form data and compare to the given {@code MultiValueMap}.
 * @since 4.3
 */
public RequestMatcher formData(final MultiValueMap<String, String> expectedContent) {
	return request -> {
		HttpInputMessage inputMessage = new HttpInputMessage() {
			@Override
			public InputStream getBody() throws IOException {
				MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
				return new ByteArrayInputStream(mockRequest.getBodyAsBytes());
			}
			@Override
			public HttpHeaders getHeaders() {
				return request.getHeaders();
			}
		};
		FormHttpMessageConverter converter = new FormHttpMessageConverter();
		assertEquals("Request content", expectedContent, converter.read(null, inputMessage));
	};
}
 
@Override
@SuppressWarnings("unchecked")
protected T readInternal(Class<? extends T> clazz, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	WireFeedInput feedInput = new WireFeedInput();
	MediaType contentType = inputMessage.getHeaders().getContentType();
	Charset charset = (contentType != null && contentType.getCharset() != null ?
			contentType.getCharset() : DEFAULT_CHARSET);
	try {
		Reader reader = new InputStreamReader(inputMessage.getBody(), charset);
		return (T) feedInput.build(reader);
	}
	catch (FeedException ex) {
		throw new HttpMessageNotReadableException("Could not read WireFeed: " + ex.getMessage(), ex, inputMessage);
	}
}
 
@Test
public void resolveArgument() throws Exception {
	MediaType contentType = MediaType.TEXT_PLAIN;
	servletRequest.addHeader("Content-Type", contentType.toString());

	String body = "Foo";
	servletRequest.setContent(body.getBytes(StandardCharsets.UTF_8));

	given(stringMessageConverter.canRead(String.class, contentType)).willReturn(true);
	given(stringMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(body);

	Object result = processor.resolveArgument(paramRequestBodyString, mavContainer,
			webRequest, new ValidatingBinderFactory());

	assertEquals("Invalid argument", body, result);
	assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled());
}
 
@Test
@SuppressWarnings("unchecked")
public void generics() throws IOException {
	GenericHttpMessageConverter<String> converter = mock(GenericHttpMessageConverter.class);
	HttpHeaders responseHeaders = new HttpHeaders();
	MediaType contentType = MediaType.TEXT_PLAIN;
	responseHeaders.setContentType(contentType);
	String expected = "Foo";
	ParameterizedTypeReference<List<String>> reference = new ParameterizedTypeReference<List<String>>() {};
	Type type = reference.getType();
	extractor = new HttpMessageConverterExtractor<List<String>>(type, createConverterList(converter));
	given(response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream(expected.getBytes()));
	given(converter.canRead(type, null, contentType)).willReturn(true);
	given(converter.read(eq(type), eq(null), any(HttpInputMessage.class))).willReturn(expected);

	Object result = extractor.extractData(response);
	assertEquals(expected, result);
}
 
@Test  // SPR-13592
@SuppressWarnings("unchecked")
public void converterThrowsIOException() throws IOException {
	HttpMessageConverter<String> converter = mock(HttpMessageConverter.class);
	HttpHeaders responseHeaders = new HttpHeaders();
	MediaType contentType = MediaType.TEXT_PLAIN;
	responseHeaders.setContentType(contentType);
	extractor = new HttpMessageConverterExtractor<>(String.class, createConverterList(converter));
	given(response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream("Foobar".getBytes()));
	given(converter.canRead(String.class, contentType)).willReturn(true);
	given(converter.read(eq(String.class), any(HttpInputMessage.class))).willThrow(IOException.class);
	assertThatExceptionOfType(RestClientException.class).isThrownBy(() ->
			extractor.extractData(response))
		.withMessageContaining("Error while extracting response for type [class java.lang.String] and content type [text/plain]")
		.withCauseInstanceOf(IOException.class);
}
 
private MultiValueMap<String, String> parseFormData(final MediaType mediaType) {
	HttpInputMessage message = new HttpInputMessage() {
		@Override
		public InputStream getBody() {
			return (content != null ? new ByteArrayInputStream(content) : StreamUtils.emptyInput());
		}
		@Override
		public HttpHeaders getHeaders() {
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(mediaType);
			return headers;
		}
	};

	try {
		return new FormHttpMessageConverter().read(null, message);
	}
	catch (IOException ex) {
		throw new IllegalStateException("Failed to parse form data in request body", ex);
	}
}
 
@Override
protected QuoteWrapper readInternal(Class<? extends QuoteWrapper> clazz, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
    CSVReader reader = new CSVReader(new InputStreamReader(httpInputMessage.getBody()));
    List<String[]> rows = reader.readAll();
    QuoteWrapper quoteWrapper = new QuoteWrapper();
    for (String[] row : rows) {

    	quoteWrapper.add(new YahooQuote(row[0], 
    								row[1], 
    								parseDouble(row[2]), 
    								parseDouble(row[3]), 
    								parseDouble(row[4]), 
    								parseDouble(row[5]), 
    								parsePercent(row[6]), 
    								parseDouble(row[7]), 
    								parseDouble(row[8]), 
    								parseDouble(row[9]), 
    								parseDouble(row[10]), 
    								parseInt(row[11]), 
    								row[12], 
    								row[13]));
    }

    return quoteWrapper;
}
 
@Override
protected QuoteWrapper readInternal(Class<? extends QuoteWrapper> clazz, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
    CSVReader reader = new CSVReader(new InputStreamReader(httpInputMessage.getBody()));
    List<String[]> rows = reader.readAll();
    QuoteWrapper quoteWrapper = new QuoteWrapper();
    for (String[] row : rows) {
    	quoteWrapper.add(new YahooQuote(row[0], 
    								row[1], 
    								parseDouble(row[2]), 
    								parseDouble(row[3]), 
    								parseDouble(row[4]), 
    								parseDouble(row[5]), 
    								parsePercent(row[6]), 
    								parseDouble(row[7]), 
    								parseDouble(row[8]), 
    								parseDouble(row[9]), 
    								parseDouble(row[10]), 
    								parseInt(row[11]), 
    								row[12], 
    								row[13]));
    }

    return quoteWrapper;
}
 
private void testResolveArgument(SimpleBean argValue, MethodParameter parameter) throws Exception {
	given(messageConverter.canRead(SimpleBean.class, MediaType.TEXT_PLAIN)).willReturn(true);
	given(messageConverter.read(eq(SimpleBean.class), isA(HttpInputMessage.class))).willReturn(argValue);

	ModelAndViewContainer mavContainer = new ModelAndViewContainer();

	Object actualValue = resolver.resolveArgument(parameter, mavContainer, webRequest, new ValidatingBinderFactory());
	assertEquals("Invalid argument value", argValue, actualValue);
	assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled());
}
 
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter methodParameter,
		Type targetType, Class<? extends HttpMessageConverter<?>> selectedConverterType) throws IOException {

	JsonView ann = methodParameter.getParameterAnnotation(JsonView.class);
	Assert.state(ann != null, "No JsonView annotation");

	Class<?>[] classes = ann.value();
	if (classes.length != 1) {
		throw new IllegalArgumentException(
				"@JsonView only supported for request body advice with exactly 1 class argument: " + methodParameter);
	}

	return new MappingJacksonInputMessage(inputMessage.getBody(), inputMessage.getHeaders(), classes[0]);
}
 
/**
 * The default implementation returns the InputMessage that was passed in.
 */
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter,
		Type targetType, Class<? extends HttpMessageConverter<?>> converterType)
		throws IOException {

	return inputMessage;
}
 
private Object[] provideParamsForCanHandle() {
    return p(
        p(null, false),
        p(new RuntimeException(), false),
        p(new NoHandlerFoundException(null, null, null), true),
        p(new HttpMessageNotReadableException("", mock(HttpInputMessage.class)), true),
        p(new MissingServletRequestParameterException("name", "String"), true),
        p(new HttpMediaTypeNotAcceptableException(""), true),
        p(new HttpMediaTypeNotSupportedException(""), true),
        p(new HttpRequestMethodNotSupportedException(""), true),
        p(new MissingServletRequestPartException("file"), true)
    );
}
 
private void testResolveArgument(SimpleBean argValue, MethodParameter parameter) throws Exception {
	given(messageConverter.canRead(SimpleBean.class, MediaType.TEXT_PLAIN)).willReturn(true);
	given(messageConverter.read(eq(SimpleBean.class), isA(HttpInputMessage.class))).willReturn(argValue);

	ModelAndViewContainer mavContainer = new ModelAndViewContainer();
	Object actualValue = resolver.resolveArgument(parameter, mavContainer, webRequest, new ValidatingBinderFactory());

	assertEquals("Invalid argument value", argValue, actualValue);
	assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled());
}
 
源代码22 项目: springMvc4.x-project   文件: MyMessageConverter.java
/**
 * ③
 */

@Override
protected DemoObj readInternal(Class<? extends DemoObj> clazz,
		HttpInputMessage inputMessage) throws IOException,
		HttpMessageNotReadableException {
	String temp = StreamUtils.copyToString(inputMessage.getBody(),

	Charset.forName("UTF-8"));
	String[] tempArr = temp.split("-");
	return new DemoObj(new Long(tempArr[0]), tempArr[1]);
}
 
@Override
public BufferedImage read(@Nullable Class<? extends BufferedImage> clazz, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	ImageInputStream imageInputStream = null;
	ImageReader imageReader = null;
	try {
		imageInputStream = createImageInputStream(inputMessage.getBody());
		MediaType contentType = inputMessage.getHeaders().getContentType();
		if (contentType == null) {
			throw new HttpMessageNotReadableException("No Content-Type header", inputMessage);
		}
		Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(contentType.toString());
		if (imageReaders.hasNext()) {
			imageReader = imageReaders.next();
			ImageReadParam irp = imageReader.getDefaultReadParam();
			process(irp);
			imageReader.setInput(imageInputStream, true);
			return imageReader.read(0, irp);
		}
		else {
			throw new HttpMessageNotReadableException(
					"Could not find javax.imageio.ImageReader for Content-Type [" + contentType + "]",
					inputMessage);
		}
	}
	finally {
		if (imageReader != null) {
			imageReader.dispose();
		}
		if (imageInputStream != null) {
			try {
				imageInputStream.close();
			}
			catch (IOException ex) {
				// ignore
			}
		}
	}
}
 
@Test(expected = HttpMessageNotReadableException.class)  // SPR-9942
public void resolveArgumentRequiredNoContent() throws Exception {
	servletRequest.setContentType(MediaType.TEXT_PLAIN_VALUE);
	servletRequest.setContent(new byte[0]);
	given(stringMessageConverter.canRead(String.class, MediaType.TEXT_PLAIN)).willReturn(true);
	given(stringMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(null);
	assertNull(processor.resolveArgument(paramRequestBodyString, mavContainer,
			webRequest, new ValidatingBinderFactory()));
}
 
源代码25 项目: spring4-understanding   文件: RestTemplateTests.java
@Test
public void getForObject() throws Exception {
	given(converter.canRead(String.class, null)).willReturn(true);
	MediaType textPlain = new MediaType("text", "plain");
	given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain));
	given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET)).willReturn(request);
	HttpHeaders requestHeaders = new HttpHeaders();
	given(request.getHeaders()).willReturn(requestHeaders);
	given(request.execute()).willReturn(response);
	given(errorHandler.hasError(response)).willReturn(false);
	String expected = "Hello World";
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setContentType(textPlain);
	responseHeaders.setContentLength(10);
	given(response.getStatusCode()).willReturn(HttpStatus.OK);
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream(expected.getBytes()));
	given(converter.canRead(String.class, textPlain)).willReturn(true);
	given(converter.read(eq(String.class), any(HttpInputMessage.class))).willReturn(expected);
	HttpStatus status = HttpStatus.OK;
	given(response.getStatusCode()).willReturn(status);
	given(response.getStatusText()).willReturn(status.getReasonPhrase());

	String result = template.getForObject("http://example.com", String.class);
	assertEquals("Invalid GET result", expected, result);
	assertEquals("Invalid Accept header", textPlain.toString(), requestHeaders.getFirst("Accept"));

	verify(response).close();
}
 
@Override
public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {
	String json = IOUtils.toString(inputMessage.getBody(), getCharset(inputMessage.getHeaders()));
	DefaultJSONParser parser = new DefaultJSONParser(json, this.parserConfig);
	Object value = parser.parseObject(type);

	parser.handleResovleTask(value);

	parser.close();

	return value;
}
 
源代码27 项目: lams   文件: GsonHttpMessageConverter.java
@Override
@SuppressWarnings("deprecation")
public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	TypeToken<?> token = getTypeToken(type);
	return readTypeToken(token, inputMessage);
}
 
源代码28 项目: springMvc4.x-project   文件: MyMessageConverter.java
/**
 * ③
 */

@Override
protected DemoObj readInternal(Class<? extends DemoObj> clazz,
		HttpInputMessage inputMessage) throws IOException,
		HttpMessageNotReadableException {
	String temp = StreamUtils.copyToString(inputMessage.getBody(),

	Charset.forName("UTF-8"));
	String[] tempArr = temp.split("-");
	return new DemoObj(new Long(tempArr[0]), tempArr[1]);
}
 
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage request, MethodParameter parameter,
		Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {

	for (RequestBodyAdvice advice : getMatchingAdvice(parameter, RequestBodyAdvice.class)) {
		if (advice.supports(parameter, targetType, converterType)) {
			request = advice.beforeBodyRead(request, parameter, targetType, converterType);
		}
	}
	return request;
}
 
@Override
protected String readInternal(Class<? extends String> clazz,
		HttpInputMessage inputMessage) throws IOException,
		HttpMessageNotReadableException {
	MediaType contentType = inputMessage.getHeaders().getContentType();
	Charset charset = contentType.getCharSet() != null ? contentType.getCharSet() : DEFAULT_CHARSET;
	return FileCopyUtils.copyToString(new InputStreamReader(inputMessage.getBody(), charset));
}
 
 类所在包
 同包方法