Here are the examples of the java api org.springframework.http.client.ClientHttpResponse taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
209 Examples
19
Source : EnhancerClientHttpResponse.java
with Apache License 2.0
from yin5980280
with Apache License 2.0
from yin5980280
/**
* client response 代理
*
* @author yinlin
*/
public clreplaced EnhancerClientHttpResponse implements ClientHttpResponse {
private ClientHttpResponse clientHttpResponse;
/**
* 原始响应体
*/
private String responseText;
private InputStream inputStream;
public EnhancerClientHttpResponse(ClientHttpResponse clientHttpResponse) {
this.clientHttpResponse = clientHttpResponse;
}
public String responseText() {
try {
responseText = IOUtils.toString(clientHttpResponse.getBody(), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return responseText;
}
@Override
public InputStream getBody() throws IOException {
inputStream = IOUtils.toInputStream(responseText, "UTF-8");
return inputStream;
}
@Override
public HttpHeaders getHeaders() {
return clientHttpResponse.getHeaders();
}
@Override
public HttpStatus getStatusCode() throws IOException {
return clientHttpResponse.getStatusCode();
}
@Override
public int getRawStatusCode() throws IOException {
return clientHttpResponse.getRawStatusCode();
}
@Override
public String getStatusText() throws IOException {
return clientHttpResponse.getStatusText();
}
@Override
public void close() {
clientHttpResponse.close();
IOUtils.closeQuietly(inputStream);
}
}
19
Source : RestTemplateXhrTransportTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test
public void connectReceiveAndCloseWithPrelude() throws Exception {
StringBuilder sb = new StringBuilder(2048);
for (int i = 0; i < 2048; i++) {
sb.append('h');
}
String body = sb.toString() + "\n" + "o\n" + "a[\"foo\"]\n" + "c[3000,\"Go away!\"]";
ClientHttpResponse response = response(HttpStatus.OK, body);
connect(response);
verify(this.webSocketHandler).afterConnectionEstablished(any());
verify(this.webSocketHandler).handleMessage(any(), eq(new TextMessage("foo")));
verify(this.webSocketHandler).afterConnectionClosed(any(), eq(new CloseStatus(3000, "Go away!")));
verifyNoMoreInteractions(this.webSocketHandler);
}
19
Source : RestTemplateXhrTransportTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test
public void responseClosedAfterDisconnected() throws Exception {
String body = "o\n" + "c[3000,\"Go away!\"]\n" + "a[\"foo\"]\n";
ClientHttpResponse response = response(HttpStatus.OK, body);
connect(response);
verify(this.webSocketHandler).afterConnectionEstablished(any());
verify(this.webSocketHandler).afterConnectionClosed(any(), any());
verifyNoMoreInteractions(this.webSocketHandler);
verify(response).close();
}
19
Source : RestTemplateXhrTransportTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test
public void connectReceiveAndClose() throws Exception {
String body = "o\n" + "a[\"foo\"]\n" + "c[3000,\"Go away!\"]";
ClientHttpResponse response = response(HttpStatus.OK, body);
connect(response);
verify(this.webSocketHandler).afterConnectionEstablished(any());
verify(this.webSocketHandler).handleMessage(any(), eq(new TextMessage("foo")));
verify(this.webSocketHandler).afterConnectionClosed(any(), eq(new CloseStatus(3000, "Go away!")));
verifyNoMoreInteractions(this.webSocketHandler);
}
19
Source : RestTemplateXhrTransportTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
private ListenableFuture<WebSocketSession> connect(ClientHttpResponse... responses) throws Exception {
return connect(new TestRestTemplate(responses));
}
19
Source : HttpMessageConverterExtractorTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
/**
* Test fixture for {@link HttpMessageConverter}.
*
* @author Arjen Poutsma
* @author Brian Clozel
*/
public clreplaced HttpMessageConverterExtractorTests {
private HttpMessageConverterExtractor<?> extractor;
private final ClientHttpResponse response = mock(ClientHttpResponse.clreplaced);
@Test
public void noContent() throws IOException {
HttpMessageConverter<?> converter = mock(HttpMessageConverter.clreplaced);
extractor = new HttpMessageConverterExtractor<>(String.clreplaced, createConverterList(converter));
given(response.getRawStatusCode()).willReturn(HttpStatus.NO_CONTENT.value());
Object result = extractor.extractData(response);
replacedertNull(result);
}
@Test
public void notModified() throws IOException {
HttpMessageConverter<?> converter = mock(HttpMessageConverter.clreplaced);
extractor = new HttpMessageConverterExtractor<>(String.clreplaced, createConverterList(converter));
given(response.getRawStatusCode()).willReturn(HttpStatus.NOT_MODIFIED.value());
Object result = extractor.extractData(response);
replacedertNull(result);
}
@Test
public void informational() throws IOException {
HttpMessageConverter<?> converter = mock(HttpMessageConverter.clreplaced);
extractor = new HttpMessageConverterExtractor<>(String.clreplaced, createConverterList(converter));
given(response.getRawStatusCode()).willReturn(HttpStatus.CONTINUE.value());
Object result = extractor.extractData(response);
replacedertNull(result);
}
@Test
public void zeroContentLength() throws IOException {
HttpMessageConverter<?> converter = mock(HttpMessageConverter.clreplaced);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentLength(0);
extractor = new HttpMessageConverterExtractor<>(String.clreplaced, createConverterList(converter));
given(response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
given(response.getHeaders()).willReturn(responseHeaders);
Object result = extractor.extractData(response);
replacedertNull(result);
}
@Test
@SuppressWarnings("unchecked")
public void emptyMessageBody() throws IOException {
HttpMessageConverter<String> converter = mock(HttpMessageConverter.clreplaced);
HttpHeaders responseHeaders = new HttpHeaders();
extractor = new HttpMessageConverterExtractor<>(String.clreplaced, createConverterList(converter));
given(response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream("".getBytes()));
Object result = extractor.extractData(response);
replacedertNull(result);
}
// gh-22265
@Test
@SuppressWarnings("unchecked")
public void nullMessageBody() throws IOException {
HttpMessageConverter<String> converter = mock(HttpMessageConverter.clreplaced);
HttpHeaders responseHeaders = new HttpHeaders();
extractor = new HttpMessageConverterExtractor<>(String.clreplaced, createConverterList(converter));
given(response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(null);
Object result = extractor.extractData(response);
replacedertNull(result);
}
@Test
@SuppressWarnings("unchecked")
public void normal() throws IOException {
HttpMessageConverter<String> converter = mock(HttpMessageConverter.clreplaced);
HttpHeaders responseHeaders = new HttpHeaders();
MediaType contentType = MediaType.TEXT_PLAIN;
responseHeaders.setContentType(contentType);
String expected = "Foo";
extractor = new HttpMessageConverterExtractor<>(String.clreplaced, 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(String.clreplaced, contentType)).willReturn(true);
given(converter.read(eq(String.clreplaced), any(HttpInputMessage.clreplaced))).willReturn(expected);
Object result = extractor.extractData(response);
replacedertEquals(expected, result);
}
@Test
@SuppressWarnings("unchecked")
public void cannotRead() throws IOException {
HttpMessageConverter<String> converter = mock(HttpMessageConverter.clreplaced);
HttpHeaders responseHeaders = new HttpHeaders();
MediaType contentType = MediaType.TEXT_PLAIN;
responseHeaders.setContentType(contentType);
extractor = new HttpMessageConverterExtractor<>(String.clreplaced, 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.clreplaced, contentType)).willReturn(false);
replacedertThatExceptionOfType(RestClientException.clreplaced).isThrownBy(() -> extractor.extractData(response));
}
@Test
@SuppressWarnings("unchecked")
public void generics() throws IOException {
GenericHttpMessageConverter<String> converter = mock(GenericHttpMessageConverter.clreplaced);
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.clreplaced))).willReturn(expected);
Object result = extractor.extractData(response);
replacedertEquals(expected, result);
}
// SPR-13592
@Test
@SuppressWarnings("unchecked")
public void converterThrowsIOException() throws IOException {
HttpMessageConverter<String> converter = mock(HttpMessageConverter.clreplaced);
HttpHeaders responseHeaders = new HttpHeaders();
MediaType contentType = MediaType.TEXT_PLAIN;
responseHeaders.setContentType(contentType);
extractor = new HttpMessageConverterExtractor<>(String.clreplaced, 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.clreplaced, contentType)).willReturn(true);
given(converter.read(eq(String.clreplaced), any(HttpInputMessage.clreplaced))).willThrow(IOException.clreplaced);
replacedertThatExceptionOfType(RestClientException.clreplaced).isThrownBy(() -> extractor.extractData(response)).withMessageContaining("Error while extracting response for type [clreplaced java.lang.String] and content type [text/plain]").withCauseInstanceOf(IOException.clreplaced);
}
// SPR-13592
@Test
@SuppressWarnings("unchecked")
public void converterThrowsHttpMessageNotReadableException() throws IOException {
HttpMessageConverter<String> converter = mock(HttpMessageConverter.clreplaced);
HttpHeaders responseHeaders = new HttpHeaders();
MediaType contentType = MediaType.TEXT_PLAIN;
responseHeaders.setContentType(contentType);
extractor = new HttpMessageConverterExtractor<>(String.clreplaced, 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.clreplaced, contentType)).willThrow(HttpMessageNotReadableException.clreplaced);
replacedertThatExceptionOfType(RestClientException.clreplaced).isThrownBy(() -> extractor.extractData(response)).withMessageContaining("Error while extracting response for type [clreplaced java.lang.String] and content type [text/plain]").withCauseInstanceOf(HttpMessageNotReadableException.clreplaced);
}
private List<HttpMessageConverter<?>> createConverterList(HttpMessageConverter<?> converter) {
List<HttpMessageConverter<?>> converters = new ArrayList<>(1);
converters.add(converter);
return converters;
}
}
19
Source : ExtractingResponseErrorHandlerTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
/**
* @author Arjen Poutsma
*/
public clreplaced ExtractingResponseErrorHandlerTests {
private ExtractingResponseErrorHandler errorHandler;
private final ClientHttpResponse response = mock(ClientHttpResponse.clreplaced);
@Before
public void setup() throws Exception {
HttpMessageConverter<Object> converter = new MappingJackson2HttpMessageConverter();
this.errorHandler = new ExtractingResponseErrorHandler(Collections.singletonList(converter));
this.errorHandler.setStatusMapping(Collections.singletonMap(HttpStatus.I_AM_A_TEAPOT, MyRestClientException.clreplaced));
this.errorHandler.setSeriesMapping(Collections.singletonMap(HttpStatus.Series.SERVER_ERROR, MyRestClientException.clreplaced));
}
@Test
public void hasError() throws Exception {
given(this.response.getRawStatusCode()).willReturn(HttpStatus.I_AM_A_TEAPOT.value());
replacedertTrue(this.errorHandler.hasError(this.response));
given(this.response.getRawStatusCode()).willReturn(HttpStatus.INTERNAL_SERVER_ERROR.value());
replacedertTrue(this.errorHandler.hasError(this.response));
given(this.response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
replacedertFalse(this.errorHandler.hasError(this.response));
}
@Test
public void hasErrorOverride() throws Exception {
this.errorHandler.setSeriesMapping(Collections.singletonMap(HttpStatus.Series.CLIENT_ERROR, null));
given(this.response.getRawStatusCode()).willReturn(HttpStatus.I_AM_A_TEAPOT.value());
replacedertTrue(this.errorHandler.hasError(this.response));
given(this.response.getRawStatusCode()).willReturn(HttpStatus.NOT_FOUND.value());
replacedertFalse(this.errorHandler.hasError(this.response));
given(this.response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
replacedertFalse(this.errorHandler.hasError(this.response));
}
@Test
public void handleErrorStatusMatch() throws Exception {
given(this.response.getRawStatusCode()).willReturn(HttpStatus.I_AM_A_TEAPOT.value());
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
given(this.response.getHeaders()).willReturn(responseHeaders);
byte[] body = "{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8);
responseHeaders.setContentLength(body.length);
given(this.response.getBody()).willReturn(new ByteArrayInputStream(body));
try {
this.errorHandler.handleError(this.response);
fail("MyRestClientException expected");
} catch (MyRestClientException ex) {
replacedertEquals("bar", ex.getFoo());
}
}
@Test
public void handleErrorSeriesMatch() throws Exception {
given(this.response.getRawStatusCode()).willReturn(HttpStatus.INTERNAL_SERVER_ERROR.value());
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
given(this.response.getHeaders()).willReturn(responseHeaders);
byte[] body = "{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8);
responseHeaders.setContentLength(body.length);
given(this.response.getBody()).willReturn(new ByteArrayInputStream(body));
try {
this.errorHandler.handleError(this.response);
fail("MyRestClientException expected");
} catch (MyRestClientException ex) {
replacedertEquals("bar", ex.getFoo());
}
}
@Test
public void handleNoMatch() throws Exception {
given(this.response.getRawStatusCode()).willReturn(HttpStatus.NOT_FOUND.value());
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
given(this.response.getHeaders()).willReturn(responseHeaders);
byte[] body = "{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8);
responseHeaders.setContentLength(body.length);
given(this.response.getBody()).willReturn(new ByteArrayInputStream(body));
try {
this.errorHandler.handleError(this.response);
fail("HttpClientErrorException expected");
} catch (HttpClientErrorException ex) {
replacedertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
replacedertArrayEquals(body, ex.getResponseBodyAsByteArray());
}
}
@Test
public void handleNoMatchOverride() throws Exception {
this.errorHandler.setSeriesMapping(Collections.singletonMap(HttpStatus.Series.CLIENT_ERROR, null));
given(this.response.getRawStatusCode()).willReturn(HttpStatus.NOT_FOUND.value());
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
given(this.response.getHeaders()).willReturn(responseHeaders);
byte[] body = "{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8);
responseHeaders.setContentLength(body.length);
given(this.response.getBody()).willReturn(new ByteArrayInputStream(body));
this.errorHandler.handleError(this.response);
}
@SuppressWarnings("serial")
private static clreplaced MyRestClientException extends RestClientException {
private String foo;
public MyRestClientException(String msg) {
super(msg);
}
public MyRestClientException(String msg, Throwable ex) {
super(msg, ex);
}
public String getFoo() {
return this.foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
}
}
19
Source : DefaultResponseErrorHandlerTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
/**
* Unit tests for {@link DefaultResponseErrorHandler}.
*
* @author Arjen Poutsma
* @author Juergen Hoeller
* @author Denys Ivano
*/
public clreplaced DefaultResponseErrorHandlerTests {
private final DefaultResponseErrorHandler handler = new DefaultResponseErrorHandler();
private final ClientHttpResponse response = mock(ClientHttpResponse.clreplaced);
@Test
public void hasErrorTrue() throws Exception {
given(response.getRawStatusCode()).willReturn(HttpStatus.NOT_FOUND.value());
replacedertTrue(handler.hasError(response));
}
@Test
public void hasErrorFalse() throws Exception {
given(response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
replacedertFalse(handler.hasError(response));
}
@Test
public void handleError() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getRawStatusCode()).willReturn(HttpStatus.NOT_FOUND.value());
given(response.getStatusText()).willReturn("Not Found");
given(response.getHeaders()).willReturn(headers);
given(response.getBody()).willReturn(new ByteArrayInputStream("Hello World".getBytes(StandardCharsets.UTF_8)));
try {
handler.handleError(response);
fail("expected HttpClientErrorException");
} catch (HttpClientErrorException ex) {
replacedertSame(headers, ex.getResponseHeaders());
}
}
@Test(expected = HttpClientErrorException.clreplaced)
public void handleErrorIOException() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getRawStatusCode()).willReturn(HttpStatus.NOT_FOUND.value());
given(response.getStatusText()).willReturn("Not Found");
given(response.getHeaders()).willReturn(headers);
given(response.getBody()).willThrow(new IOException());
handler.handleError(response);
}
@Test(expected = HttpClientErrorException.clreplaced)
public void handleErrorNullResponse() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getRawStatusCode()).willReturn(HttpStatus.NOT_FOUND.value());
given(response.getStatusText()).willReturn("Not Found");
given(response.getHeaders()).willReturn(headers);
handler.handleError(response);
}
// SPR-16108
@Test
public void hasErrorForUnknownStatusCode() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getRawStatusCode()).willReturn(999);
given(response.getStatusText()).willReturn("Custom status code");
given(response.getHeaders()).willReturn(headers);
replacedertFalse(handler.hasError(response));
}
// SPR-9406
@Test(expected = UnknownHttpStatusCodeException.clreplaced)
public void handleErrorUnknownStatusCode() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getRawStatusCode()).willReturn(999);
given(response.getStatusText()).willReturn("Custom status code");
given(response.getHeaders()).willReturn(headers);
handler.handleError(response);
}
// SPR-17461
@Test
public void hasErrorForCustomClientError() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getRawStatusCode()).willReturn(499);
given(response.getStatusText()).willReturn("Custom status code");
given(response.getHeaders()).willReturn(headers);
replacedertTrue(handler.hasError(response));
}
@Test(expected = UnknownHttpStatusCodeException.clreplaced)
public void handleErrorForCustomClientError() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getRawStatusCode()).willReturn(499);
given(response.getStatusText()).willReturn("Custom status code");
given(response.getHeaders()).willReturn(headers);
handler.handleError(response);
}
// SPR-17461
@Test
public void hasErrorForCustomServerError() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getRawStatusCode()).willReturn(599);
given(response.getStatusText()).willReturn("Custom status code");
given(response.getHeaders()).willReturn(headers);
replacedertTrue(handler.hasError(response));
}
@Test(expected = UnknownHttpStatusCodeException.clreplaced)
public void handleErrorForCustomServerError() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getRawStatusCode()).willReturn(599);
given(response.getStatusText()).willReturn("Custom status code");
given(response.getHeaders()).willReturn(headers);
handler.handleError(response);
}
// SPR-16604
@Test
public void bodyAvailableAfterHasErrorForUnknownStatusCode() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
TestByteArrayInputStream body = new TestByteArrayInputStream("Hello World".getBytes(StandardCharsets.UTF_8));
given(response.getRawStatusCode()).willReturn(999);
given(response.getStatusText()).willReturn("Custom status code");
given(response.getHeaders()).willReturn(headers);
given(response.getBody()).willReturn(body);
replacedertFalse(handler.hasError(response));
replacedertFalse(body.isClosed());
replacedertEquals("Hello World", StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8));
}
private static clreplaced TestByteArrayInputStream extends ByteArrayInputStream {
private boolean closed;
public TestByteArrayInputStream(byte[] buf) {
super(buf);
this.closed = false;
}
public boolean isClosed() {
return closed;
}
@Override
public boolean markSupported() {
return false;
}
@Override
public synchronized void mark(int readlimit) {
throw new UnsupportedOperationException("mark/reset not supported");
}
@Override
public synchronized void reset() {
throw new UnsupportedOperationException("mark/reset not supported");
}
@Override
public void close() throws IOException {
super.close();
this.closed = true;
}
}
}
19
Source : ExtractingResponseErrorHandler.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
private void extract(@Nullable Clreplaced<? extends RestClientException> exceptionClreplaced, ClientHttpResponse response) throws IOException {
if (exceptionClreplaced == null) {
return;
}
HttpMessageConverterExtractor<? extends RestClientException> extractor = new HttpMessageConverterExtractor<>(exceptionClreplaced, this.messageConverters);
RestClientException exception = extractor.extractData(response);
if (exception != null) {
throw exception;
}
}
19
Source : MockClientHttpRequest.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
public void setResponse(ClientHttpResponse clientHttpResponse) {
this.clientHttpResponse = clientHttpResponse;
}
19
Source : LoggingClientHttpRequestInterceptor.java
with GNU Lesser General Public License v2.1
from Verdoso
with GNU Lesser General Public License v2.1
from Verdoso
private boolean isBuffered(ClientHttpResponse response) {
// clreplaced is non-public, so we check by name
boolean buffered = "org.springframework.http.client.BufferingClientHttpResponseWrapper".equals(response.getClreplaced().getName());
if (!buffered && !loggedMissingBuffering) {
log.warn("Can't log HTTP response bodies, as you haven't configured the RestTemplate with a BufferingClientHttpRequestFactory");
loggedMissingBuffering = true;
}
return buffered;
}
19
Source : WechatErrorHandler.java
with Apache License 2.0
from venwyhk
with Apache License 2.0
from venwyhk
private void handleUncategorizedError(ClientHttpResponse response) {
try {
super.handleError(response);
} catch (Exception e) {
throw new UncategorizedApiException("wechat", "Error consuming wechat REST api", e);
}
}
19
Source : BufferingClientHttpResponseWrapper.java
with Apache License 2.0
from teiid
with Apache License 2.0
from teiid
/**
* Simple implementation of {@link ClientHttpResponse} that reads the response's body
* into memory, thus allowing for multiple invocations of {@link #getBody()}.
*
* @author Arjen Poutsma
* @since 3.1
*/
final clreplaced BufferingClientHttpResponseWrapper implements ClientHttpResponse {
private final ClientHttpResponse response;
private byte[] body;
BufferingClientHttpResponseWrapper(ClientHttpResponse response) {
this.response = response;
}
@Override
public HttpStatus getStatusCode() throws IOException {
return this.response.getStatusCode();
}
@Override
public int getRawStatusCode() throws IOException {
return this.response.getRawStatusCode();
}
@Override
public String getStatusText() throws IOException {
return this.response.getStatusText();
}
@Override
public HttpHeaders getHeaders() {
return this.response.getHeaders();
}
@Override
public InputStream getBody() throws IOException {
if (this.body == null) {
this.body = StreamUtils.copyToByteArray(this.response.getBody());
}
return new ByteArrayInputStream(this.body);
}
@Override
public void close() {
this.response.close();
}
}
19
Source : ExtractingResponseErrorHandlerTests.java
with Apache License 2.0
from SourceHot
with Apache License 2.0
from SourceHot
/**
* @author Arjen Poutsma
*/
public clreplaced ExtractingResponseErrorHandlerTests {
private ExtractingResponseErrorHandler errorHandler;
private final ClientHttpResponse response = mock(ClientHttpResponse.clreplaced);
@BeforeEach
public void setup() {
HttpMessageConverter<Object> converter = new MappingJackson2HttpMessageConverter();
this.errorHandler = new ExtractingResponseErrorHandler(Collections.singletonList(converter));
this.errorHandler.setStatusMapping(Collections.singletonMap(HttpStatus.I_AM_A_TEAPOT, MyRestClientException.clreplaced));
this.errorHandler.setSeriesMapping(Collections.singletonMap(HttpStatus.Series.SERVER_ERROR, MyRestClientException.clreplaced));
}
@Test
public void hasError() throws Exception {
given(this.response.getRawStatusCode()).willReturn(HttpStatus.I_AM_A_TEAPOT.value());
replacedertThat(this.errorHandler.hasError(this.response)).isTrue();
given(this.response.getRawStatusCode()).willReturn(HttpStatus.INTERNAL_SERVER_ERROR.value());
replacedertThat(this.errorHandler.hasError(this.response)).isTrue();
given(this.response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
replacedertThat(this.errorHandler.hasError(this.response)).isFalse();
}
@Test
public void hasErrorOverride() throws Exception {
this.errorHandler.setSeriesMapping(Collections.singletonMap(HttpStatus.Series.CLIENT_ERROR, null));
given(this.response.getRawStatusCode()).willReturn(HttpStatus.I_AM_A_TEAPOT.value());
replacedertThat(this.errorHandler.hasError(this.response)).isTrue();
given(this.response.getRawStatusCode()).willReturn(HttpStatus.NOT_FOUND.value());
replacedertThat(this.errorHandler.hasError(this.response)).isFalse();
given(this.response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
replacedertThat(this.errorHandler.hasError(this.response)).isFalse();
}
@Test
public void handleErrorStatusMatch() throws Exception {
given(this.response.getRawStatusCode()).willReturn(HttpStatus.I_AM_A_TEAPOT.value());
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
given(this.response.getHeaders()).willReturn(responseHeaders);
byte[] body = "{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8);
responseHeaders.setContentLength(body.length);
given(this.response.getBody()).willReturn(new ByteArrayInputStream(body));
replacedertThatExceptionOfType(MyRestClientException.clreplaced).isThrownBy(() -> this.errorHandler.handleError(this.response)).satisfies(ex -> replacedertThat(ex.getFoo()).isEqualTo("bar"));
}
@Test
public void handleErrorSeriesMatch() throws Exception {
given(this.response.getRawStatusCode()).willReturn(HttpStatus.INTERNAL_SERVER_ERROR.value());
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
given(this.response.getHeaders()).willReturn(responseHeaders);
byte[] body = "{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8);
responseHeaders.setContentLength(body.length);
given(this.response.getBody()).willReturn(new ByteArrayInputStream(body));
replacedertThatExceptionOfType(MyRestClientException.clreplaced).isThrownBy(() -> this.errorHandler.handleError(this.response)).satisfies(ex -> replacedertThat(ex.getFoo()).isEqualTo("bar"));
}
@Test
public void handleNoMatch() throws Exception {
given(this.response.getRawStatusCode()).willReturn(HttpStatus.NOT_FOUND.value());
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
given(this.response.getHeaders()).willReturn(responseHeaders);
byte[] body = "{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8);
responseHeaders.setContentLength(body.length);
given(this.response.getBody()).willReturn(new ByteArrayInputStream(body));
replacedertThatExceptionOfType(HttpClientErrorException.clreplaced).isThrownBy(() -> this.errorHandler.handleError(this.response)).satisfies(ex -> {
replacedertThat(ex.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
replacedertThat(ex.getResponseBodyAsByteArray()).isEqualTo(body);
});
}
@Test
public void handleNoMatchOverride() throws Exception {
this.errorHandler.setSeriesMapping(Collections.singletonMap(HttpStatus.Series.CLIENT_ERROR, null));
given(this.response.getRawStatusCode()).willReturn(HttpStatus.NOT_FOUND.value());
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
given(this.response.getHeaders()).willReturn(responseHeaders);
byte[] body = "{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8);
responseHeaders.setContentLength(body.length);
given(this.response.getBody()).willReturn(new ByteArrayInputStream(body));
this.errorHandler.handleError(this.response);
}
@SuppressWarnings("serial")
private static clreplaced MyRestClientException extends RestClientException {
private String foo;
public MyRestClientException(String msg) {
super(msg);
}
public MyRestClientException(String msg, Throwable ex) {
super(msg, ex);
}
public String getFoo() {
return this.foo;
}
}
}
19
Source : DefaultResponseErrorHandlerTests.java
with Apache License 2.0
from SourceHot
with Apache License 2.0
from SourceHot
/**
* Unit tests for {@link DefaultResponseErrorHandler}.
*
* @author Arjen Poutsma
* @author Juergen Hoeller
* @author Denys Ivano
*/
public clreplaced DefaultResponseErrorHandlerTests {
private final DefaultResponseErrorHandler handler = new DefaultResponseErrorHandler();
private final ClientHttpResponse response = mock(ClientHttpResponse.clreplaced);
@Test
public void hasErrorTrue() throws Exception {
given(response.getRawStatusCode()).willReturn(HttpStatus.NOT_FOUND.value());
replacedertThat(handler.hasError(response)).isTrue();
}
@Test
public void hasErrorFalse() throws Exception {
given(response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
replacedertThat(handler.hasError(response)).isFalse();
}
@Test
public void handleError() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getRawStatusCode()).willReturn(HttpStatus.NOT_FOUND.value());
given(response.getStatusText()).willReturn("Not Found");
given(response.getHeaders()).willReturn(headers);
given(response.getBody()).willReturn(new ByteArrayInputStream("Hello World".getBytes(StandardCharsets.UTF_8)));
replacedertThatExceptionOfType(HttpClientErrorException.clreplaced).isThrownBy(() -> handler.handleError(response)).satisfies(ex -> replacedertThat(ex.getResponseHeaders()).isSameAs(headers)).satisfies(ex -> replacedertThat(ex.getMessage()).isEqualTo("404 Not Found: [Hello World]"));
}
@Test
public void handleErrorWithLongBody() throws Exception {
Function<Integer, String> bodyGenerator = size -> Flux.just("a").repeat(size - 1).reduce((s, s2) -> s + s2).block();
given(response.getRawStatusCode()).willReturn(HttpStatus.NOT_FOUND.value());
given(response.getStatusText()).willReturn("Not Found");
given(response.getHeaders()).willReturn(new HttpHeaders());
given(response.getBody()).willReturn(new ByteArrayInputStream(bodyGenerator.apply(500).getBytes(StandardCharsets.UTF_8)));
replacedertThatExceptionOfType(HttpClientErrorException.clreplaced).isThrownBy(() -> handler.handleError(response)).satisfies(ex -> replacedertThat(ex.getMessage()).isEqualTo("404 Not Found: [" + bodyGenerator.apply(200) + "... (500 bytes)]"));
}
@Test
public void handleErrorIOException() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getRawStatusCode()).willReturn(HttpStatus.NOT_FOUND.value());
given(response.getStatusText()).willReturn("Not Found");
given(response.getHeaders()).willReturn(headers);
given(response.getBody()).willThrow(new IOException());
replacedertThatExceptionOfType(HttpClientErrorException.clreplaced).isThrownBy(() -> handler.handleError(response));
}
@Test
public void handleErrorNullResponse() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getRawStatusCode()).willReturn(HttpStatus.NOT_FOUND.value());
given(response.getStatusText()).willReturn("Not Found");
given(response.getHeaders()).willReturn(headers);
replacedertThatExceptionOfType(HttpClientErrorException.clreplaced).isThrownBy(() -> handler.handleError(response));
}
// SPR-16108
@Test
public void hasErrorForUnknownStatusCode() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getRawStatusCode()).willReturn(999);
given(response.getStatusText()).willReturn("Custom status code");
given(response.getHeaders()).willReturn(headers);
replacedertThat(handler.hasError(response)).isFalse();
}
// SPR-9406
@Test
public void handleErrorUnknownStatusCode() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getRawStatusCode()).willReturn(999);
given(response.getStatusText()).willReturn("Custom status code");
given(response.getHeaders()).willReturn(headers);
replacedertThatExceptionOfType(UnknownHttpStatusCodeException.clreplaced).isThrownBy(() -> handler.handleError(response));
}
// SPR-17461
@Test
public void hasErrorForCustomClientError() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getRawStatusCode()).willReturn(499);
given(response.getStatusText()).willReturn("Custom status code");
given(response.getHeaders()).willReturn(headers);
replacedertThat(handler.hasError(response)).isTrue();
}
@Test
public void handleErrorForCustomClientError() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getRawStatusCode()).willReturn(499);
given(response.getStatusText()).willReturn("Custom status code");
given(response.getHeaders()).willReturn(headers);
replacedertThatExceptionOfType(UnknownHttpStatusCodeException.clreplaced).isThrownBy(() -> handler.handleError(response));
}
// SPR-17461
@Test
public void hasErrorForCustomServerError() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getRawStatusCode()).willReturn(599);
given(response.getStatusText()).willReturn("Custom status code");
given(response.getHeaders()).willReturn(headers);
replacedertThat(handler.hasError(response)).isTrue();
}
@Test
public void handleErrorForCustomServerError() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getRawStatusCode()).willReturn(599);
given(response.getStatusText()).willReturn("Custom status code");
given(response.getHeaders()).willReturn(headers);
replacedertThatExceptionOfType(UnknownHttpStatusCodeException.clreplaced).isThrownBy(() -> handler.handleError(response));
}
// SPR-16604
@Test
public void bodyAvailableAfterHasErrorForUnknownStatusCode() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
TestByteArrayInputStream body = new TestByteArrayInputStream("Hello World".getBytes(StandardCharsets.UTF_8));
given(response.getRawStatusCode()).willReturn(999);
given(response.getStatusText()).willReturn("Custom status code");
given(response.getHeaders()).willReturn(headers);
given(response.getBody()).willReturn(body);
replacedertThat(handler.hasError(response)).isFalse();
replacedertThat(body.isClosed()).isFalse();
replacedertThat(StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8)).isEqualTo("Hello World");
}
private static clreplaced TestByteArrayInputStream extends ByteArrayInputStream {
private boolean closed;
public TestByteArrayInputStream(byte[] buf) {
super(buf);
this.closed = false;
}
public boolean isClosed() {
return closed;
}
@Override
public boolean markSupported() {
return false;
}
@Override
public synchronized void mark(int readlimit) {
throw new UnsupportedOperationException("mark/reset not supported");
}
@Override
public synchronized void reset() {
throw new UnsupportedOperationException("mark/reset not supported");
}
@Override
public void close() throws IOException {
super.close();
this.closed = true;
}
}
}
19
Source : DefaultResponseErrorHandlerHttpStatusTests.java
with Apache License 2.0
from SourceHot
with Apache License 2.0
from SourceHot
/**
* Unit tests for {@link DefaultResponseErrorHandler} handling of specific
* HTTP status codes.
*/
clreplaced DefaultResponseErrorHandlerHttpStatusTests {
private final DefaultResponseErrorHandler handler = new DefaultResponseErrorHandler();
private final ClientHttpResponse response = mock(ClientHttpResponse.clreplaced);
@ParameterizedTest(name = "[{index}] error: [{0}]")
@DisplayName("hasError() returns true")
@MethodSource("errorCodes")
void hasErrorTrue(HttpStatus httpStatus) throws Exception {
given(this.response.getRawStatusCode()).willReturn(httpStatus.value());
replacedertThat(this.handler.hasError(this.response)).isTrue();
}
@ParameterizedTest(name = "[{index}] error: [{0}], exception: [{1}]")
@DisplayName("handleError() throws an exception")
@MethodSource("errorCodes")
void handleErrorException(HttpStatus httpStatus, Clreplaced<? extends Throwable> expectedExceptionClreplaced) throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(this.response.getRawStatusCode()).willReturn(httpStatus.value());
given(this.response.getHeaders()).willReturn(headers);
replacedertThatExceptionOfType(expectedExceptionClreplaced).isThrownBy(() -> this.handler.handleError(this.response));
}
static Object[][] errorCodes() {
return new Object[][] { // 4xx
{ BAD_REQUEST, HttpClientErrorException.BadRequest.clreplaced }, { UNAUTHORIZED, HttpClientErrorException.Unauthorized.clreplaced }, { FORBIDDEN, HttpClientErrorException.Forbidden.clreplaced }, { NOT_FOUND, HttpClientErrorException.NotFound.clreplaced }, { METHOD_NOT_ALLOWED, HttpClientErrorException.MethodNotAllowed.clreplaced }, { NOT_ACCEPTABLE, HttpClientErrorException.NotAcceptable.clreplaced }, { CONFLICT, HttpClientErrorException.Conflict.clreplaced }, { TOO_MANY_REQUESTS, HttpClientErrorException.TooManyRequests.clreplaced }, { UNPROCESSABLE_ENreplacedY, HttpClientErrorException.UnprocessableEnreplacedy.clreplaced }, { I_AM_A_TEAPOT, HttpClientErrorException.clreplaced }, // 5xx
{ INTERNAL_SERVER_ERROR, HttpServerErrorException.InternalServerError.clreplaced }, { NOT_IMPLEMENTED, HttpServerErrorException.NotImplemented.clreplaced }, { BAD_GATEWAY, HttpServerErrorException.BadGateway.clreplaced }, { SERVICE_UNAVAILABLE, HttpServerErrorException.ServiceUnavailable.clreplaced }, { GATEWAY_TIMEOUT, HttpServerErrorException.GatewayTimeout.clreplaced }, { HTTP_VERSION_NOT_SUPPORTED, HttpServerErrorException.clreplaced } };
}
}
19
Source : CamundaClientErrorHandlerTest.java
with Apache License 2.0
from onap
with Apache License 2.0
from onap
public clreplaced CamundaClientErrorHandlerTest {
private ClientHttpResponse clientHttpResponse;
private CamundaClientErrorHandler clientErrorHandler;
@Before
public void before() {
clientHttpResponse = Mockito.mock(ClientHttpResponse.clreplaced);
clientErrorHandler = new CamundaClientErrorHandler();
}
@Test
public void handleError_SERVER_ERROR_Test() throws IOException {
Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.INTERNAL_SERVER_ERROR);
Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes()));
clientErrorHandler.handleError(clientHttpResponse);
boolean serverHasError = clientErrorHandler.hasError(clientHttpResponse);
replacedertEquals(true, serverHasError);
}
@Test
public void handleError_CLIENT_ERROR_Test() throws IOException {
Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.BAD_REQUEST);
Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes()));
clientErrorHandler.handleError(clientHttpResponse);
boolean clientHasError = clientErrorHandler.hasError(clientHttpResponse);
replacedertEquals(true, clientHasError);
}
@Test
public void handleError_SUCCESS_Test() throws IOException {
Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.ACCEPTED);
Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes()));
clientErrorHandler.handleError(clientHttpResponse);
boolean hasNoError = clientErrorHandler.hasError(clientHttpResponse);
replacedertEquals(false, hasNoError);
}
}
19
Source : UMAErrorHandler.java
with Apache License 2.0
from mposolda
with Apache License 2.0
from mposolda
public void superHandleError(ClientHttpResponse response) throws IOException {
super.handleError(response);
}
19
Source : HttpMessageConverterExtractorTests.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
/**
* Test fixture for {@link HttpMessageConverter}.
*
* @author Arjen Poutsma
*/
public clreplaced HttpMessageConverterExtractorTests {
private HttpMessageConverterExtractor<?> extractor;
private ClientHttpResponse response;
@Before
public void createMocks() {
response = mock(ClientHttpResponse.clreplaced);
}
@Test
public void noContent() throws IOException {
HttpMessageConverter<?> converter = mock(HttpMessageConverter.clreplaced);
extractor = new HttpMessageConverterExtractor<String>(String.clreplaced, createConverterList(converter));
given(response.getStatusCode()).willReturn(HttpStatus.NO_CONTENT);
Object result = extractor.extractData(response);
replacedertNull(result);
}
@Test
public void notModified() throws IOException {
HttpMessageConverter<?> converter = mock(HttpMessageConverter.clreplaced);
extractor = new HttpMessageConverterExtractor<String>(String.clreplaced, createConverterList(converter));
given(response.getStatusCode()).willReturn(HttpStatus.NOT_MODIFIED);
Object result = extractor.extractData(response);
replacedertNull(result);
}
@Test
public void informational() throws IOException {
HttpMessageConverter<?> converter = mock(HttpMessageConverter.clreplaced);
extractor = new HttpMessageConverterExtractor<String>(String.clreplaced, createConverterList(converter));
given(response.getStatusCode()).willReturn(HttpStatus.CONTINUE);
Object result = extractor.extractData(response);
replacedertNull(result);
}
@Test
public void zeroContentLength() throws IOException {
HttpMessageConverter<?> converter = mock(HttpMessageConverter.clreplaced);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentLength(0);
extractor = new HttpMessageConverterExtractor<String>(String.clreplaced, createConverterList(converter));
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
Object result = extractor.extractData(response);
replacedertNull(result);
}
@Test
@SuppressWarnings("unchecked")
public void emptyMessageBody() throws IOException {
HttpMessageConverter<String> converter = mock(HttpMessageConverter.clreplaced);
List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
converters.add(converter);
HttpHeaders responseHeaders = new HttpHeaders();
extractor = new HttpMessageConverterExtractor<String>(String.clreplaced, createConverterList(converter));
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream("".getBytes()));
Object result = extractor.extractData(response);
replacedertNull(result);
}
@Test
@SuppressWarnings("unchecked")
public void normal() throws IOException {
HttpMessageConverter<String> converter = mock(HttpMessageConverter.clreplaced);
List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
converters.add(converter);
HttpHeaders responseHeaders = new HttpHeaders();
MediaType contentType = MediaType.TEXT_PLAIN;
responseHeaders.setContentType(contentType);
String expected = "Foo";
extractor = new HttpMessageConverterExtractor<String>(String.clreplaced, converters);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream(expected.getBytes()));
given(converter.canRead(String.clreplaced, contentType)).willReturn(true);
given(converter.read(eq(String.clreplaced), any(HttpInputMessage.clreplaced))).willReturn(expected);
Object result = extractor.extractData(response);
replacedertEquals(expected, result);
}
@Test(expected = RestClientException.clreplaced)
@SuppressWarnings("unchecked")
public void cannotRead() throws IOException {
HttpMessageConverter<String> converter = mock(HttpMessageConverter.clreplaced);
List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
converters.add(converter);
HttpHeaders responseHeaders = new HttpHeaders();
MediaType contentType = MediaType.TEXT_PLAIN;
responseHeaders.setContentType(contentType);
extractor = new HttpMessageConverterExtractor<String>(String.clreplaced, converters);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream("Foobar".getBytes()));
given(converter.canRead(String.clreplaced, contentType)).willReturn(false);
extractor.extractData(response);
}
@Test
@SuppressWarnings("unchecked")
public void generics() throws IOException {
GenericHttpMessageConverter<String> converter = mock(GenericHttpMessageConverter.clreplaced);
List<HttpMessageConverter<?>> converters = createConverterList(converter);
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, converters);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
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.clreplaced))).willReturn(expected);
Object result = extractor.extractData(response);
replacedertEquals(expected, result);
}
private List<HttpMessageConverter<?>> createConverterList(HttpMessageConverter<?> converter) {
List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>(1);
converters.add(converter);
return converters;
}
}
19
Source : DefaultResponseErrorHandlerTests.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
/**
* Unit tests for {@link DefaultResponseErrorHandler}.
*
* @author Arjen Poutsma
*/
public clreplaced DefaultResponseErrorHandlerTests {
private DefaultResponseErrorHandler handler;
private ClientHttpResponse response;
@Before
public void setUp() throws Exception {
handler = new DefaultResponseErrorHandler();
response = mock(ClientHttpResponse.clreplaced);
}
@Test
public void hasErrorTrue() throws Exception {
given(response.getStatusCode()).willReturn(HttpStatus.NOT_FOUND);
replacedertTrue(handler.hasError(response));
}
@Test
public void hasErrorFalse() throws Exception {
given(response.getStatusCode()).willReturn(HttpStatus.OK);
replacedertFalse(handler.hasError(response));
}
@Test
public void handleError() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getStatusCode()).willReturn(HttpStatus.NOT_FOUND);
given(response.getStatusText()).willReturn("Not Found");
given(response.getHeaders()).willReturn(headers);
given(response.getBody()).willReturn(new ByteArrayInputStream("Hello World".getBytes("UTF-8")));
try {
handler.handleError(response);
fail("expected HttpClientErrorException");
} catch (HttpClientErrorException e) {
replacedertSame(headers, e.getResponseHeaders());
}
}
@Test(expected = HttpClientErrorException.clreplaced)
public void handleErrorIOException() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getStatusCode()).willReturn(HttpStatus.NOT_FOUND);
given(response.getStatusText()).willReturn("Not Found");
given(response.getHeaders()).willReturn(headers);
given(response.getBody()).willThrow(new IOException());
handler.handleError(response);
}
@Test(expected = HttpClientErrorException.clreplaced)
public void handleErrorNullResponse() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getStatusCode()).willReturn(HttpStatus.NOT_FOUND);
given(response.getStatusText()).willReturn("Not Found");
given(response.getHeaders()).willReturn(headers);
handler.handleError(response);
}
// SPR-9406
@Test(expected = UnknownHttpStatusCodeException.clreplaced)
public void unknownStatusCode() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
given(response.getStatusCode()).willThrow(new IllegalArgumentException("No matching constant for 999"));
given(response.getRawStatusCode()).willReturn(999);
given(response.getStatusText()).willReturn("Custom status code");
given(response.getHeaders()).willReturn(headers);
handler.handleError(response);
}
}
19
Source : TestRestTemplate.java
with Apache License 2.0
from i-novus-llc
with Apache License 2.0
from i-novus-llc
public clreplaced TestRestTemplate extends RestTemplate {
private String query;
private Object requestBody;
private ClientHttpResponse mockResponse;
public TestRestTemplate(ClientHttpResponse mockResponse) {
this.mockResponse = mockResponse;
}
public TestRestTemplate(String mockResponseBody) {
this.mockResponse = new MockClientHttpResponse(mockResponseBody.getBytes(StandardCharsets.UTF_8), HttpStatus.OK);
}
@Override
public <T> RequestCallback httpEnreplacedyCallback(Object requestBody, Type responseType) {
this.requestBody = requestBody;
return super.httpEnreplacedyCallback(requestBody, responseType);
}
public String getQuery() {
return query;
}
public Object getRequestBody() {
return (requestBody instanceof HttpEnreplacedy ? ((HttpEnreplacedy) requestBody).getBody() : requestBody);
}
public Object getRequestHeader() {
return (requestBody instanceof HttpEnreplacedy ? ((HttpEnreplacedy) requestBody).getHeaders() : Collections.EMPTY_MAP);
}
@Override
protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
this.query = url.toString();
MockClientHttpRequest mockRequest = new MockClientHttpRequest(method, url);
mockRequest.setResponse(mockResponse);
return mockRequest;
}
}
18
Source : HttpHeaderInterceptorTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
@Test
public void intercept() throws IOException {
ClientHttpResponse result = this.interceptor.intercept(this.request, this.body, this.execution);
replacedertThat(this.request.getHeaders().getFirst(this.name)).isEqualTo(this.value);
replacedertThat(result).isEqualTo(this.response);
}
18
Source : RestTemplateExchangeTags.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
private static String getStatusMessage(ClientHttpResponse response) {
try {
if (response == null) {
return "CLIENT_ERROR";
}
return String.valueOf(response.getRawStatusCode());
} catch (IOException ex) {
return "IO_ERROR";
}
}
18
Source : RestTemplateExchangeTags.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
/**
* Creates a {@code status} {@code Tag} derived from the
* {@link ClientHttpResponse#getRawStatusCode() status} of the given {@code response}.
* @param response the response
* @return the status tag
*/
public static Tag status(ClientHttpResponse response) {
return Tag.of("status", getStatusMessage(response));
}
18
Source : RestTemplateConfig.java
with Apache License 2.0
from wengwh
with Apache License 2.0
from wengwh
@Override
public void handleError(ClientHttpResponse response) throws IOException {
log.error("http request error,statusCode:{},body:{}", getHttpStatusCode(response), new String(getResponseBody(response)));
}
18
Source : JwtSsoResponseErrorHandler.java
with Apache License 2.0
from WeBankPartners
with Apache License 2.0
from WeBankPartners
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return HttpStatus.Series.CLIENT_ERROR.equals(response.getStatusCode().series()) || this.errorHandler.hasError(response);
}
18
Source : HttpRequestErrorHandler.java
with Apache License 2.0
from WeBankPartners
with Apache License 2.0
from WeBankPartners
@Override
public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {
}
18
Source : HttpRequestErrorHandler.java
with Apache License 2.0
from WeBankPartners
with Apache License 2.0
from WeBankPartners
@Override
public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
boolean hasError = false;
int rawStatusCode = clientHttpResponse.getRawStatusCode();
if (rawStatusCode != 200) {
hasError = true;
}
return hasError;
}
18
Source : RestTemplateXhrTransportTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
private ListenableFuture<WebSocketSession> connect(RestOperations restTemplate, ClientHttpResponse... responses) throws Exception {
RestTemplateXhrTransport transport = new RestTemplateXhrTransport(restTemplate);
transport.setTaskExecutor(new SyncTaskExecutor());
SockJsUrlInfo urlInfo = new SockJsUrlInfo(new URI("https://example.com"));
HttpHeaders headers = new HttpHeaders();
headers.add("h-foo", "h-bar");
TransportRequest request = new DefaultTransportRequest(urlInfo, headers, headers, transport, TransportType.XHR, CODEC);
return transport.connect(request, this.webSocketHandler);
}
18
Source : MessageBodyClientHttpResponseWrapper.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
/**
* Implementation of {@link ClientHttpResponse} that can not only check if
* the response has a message body, but also if its length is 0 (i.e. empty)
* by actually reading the input stream.
*
* @author Brian Clozel
* @since 4.1.5
* @see <a href="https://tools.ietf.org/html/rfc7230#section-3.3.3">RFC 7230 Section 3.3.3</a>
*/
clreplaced MessageBodyClientHttpResponseWrapper implements ClientHttpResponse {
private final ClientHttpResponse response;
@Nullable
private PushbackInputStream pushbackInputStream;
public MessageBodyClientHttpResponseWrapper(ClientHttpResponse response) throws IOException {
this.response = response;
}
/**
* Indicates whether the response has a message body.
* <p>Implementation returns {@code false} for:
* <ul>
* <li>a response status of {@code 1XX}, {@code 204} or {@code 304}</li>
* <li>a {@code Content-Length} header of {@code 0}</li>
* </ul>
* @return {@code true} if the response has a message body, {@code false} otherwise
* @throws IOException in case of I/O errors
*/
public boolean hasMessageBody() throws IOException {
HttpStatus status = HttpStatus.resolve(getRawStatusCode());
if (status != null && (status.is1xxInformational() || status == HttpStatus.NO_CONTENT || status == HttpStatus.NOT_MODIFIED)) {
return false;
}
if (getHeaders().getContentLength() == 0) {
return false;
}
return true;
}
/**
* Indicates whether the response has an empty message body.
* <p>Implementation tries to read the first bytes of the response stream:
* <ul>
* <li>if no bytes are available, the message body is empty</li>
* <li>otherwise it is not empty and the stream is reset to its start for further reading</li>
* </ul>
* @return {@code true} if the response has a zero-length message body, {@code false} otherwise
* @throws IOException in case of I/O errors
*/
@SuppressWarnings("ConstantConditions")
public boolean hasEmptyMessageBody() throws IOException {
InputStream body = this.response.getBody();
// Per contract body shouldn't be null, but check anyway..
if (body == null) {
return true;
}
if (body.markSupported()) {
body.mark(1);
if (body.read() == -1) {
return true;
} else {
body.reset();
return false;
}
} else {
this.pushbackInputStream = new PushbackInputStream(body);
int b = this.pushbackInputStream.read();
if (b == -1) {
return true;
} else {
this.pushbackInputStream.unread(b);
return false;
}
}
}
@Override
public HttpHeaders getHeaders() {
return this.response.getHeaders();
}
@Override
public InputStream getBody() throws IOException {
return (this.pushbackInputStream != null ? this.pushbackInputStream : this.response.getBody());
}
@Override
public HttpStatus getStatusCode() throws IOException {
return this.response.getStatusCode();
}
@Override
public int getRawStatusCode() throws IOException {
return this.response.getRawStatusCode();
}
@Override
public String getStatusText() throws IOException {
return this.response.getStatusText();
}
@Override
public void close() {
this.response.close();
}
}
18
Source : WechatErrorHandler.java
with Apache License 2.0
from venwyhk
with Apache License 2.0
from venwyhk
private Map<String, Object> extractErrorDetailsFromResponse(ClientHttpResponse response) throws IOException {
try {
return new ObjectMapper(new JsonFactory()).<Map<String, Object>>readValue(response.getBody(), new TypeReference<Map<String, Object>>() {
});
} catch (JsonParseException e) {
return Collections.emptyMap();
}
}
18
Source : OpenRestResponseErrorHandler.java
with MIT License
from uhonliu
with MIT License
from uhonliu
@Override
public boolean hasError(ClientHttpResponse clientHttpResponse) {
// false表示不管response的status是多少都返回没有错
return false;
}
18
Source : OpenRestResponseErrorHandler.java
with MIT License
from uhonliu
with MIT License
from uhonliu
@Override
public void handleError(ClientHttpResponse clientHttpResponse) {
}
18
Source : ExtendedErrorHandler.java
with Apache License 2.0
from telstra
with Apache License 2.0
from telstra
/**
* Overrides default errors and puts formatted body to the actual error message text. This helps to see
* the error response body right in the test results output without digging into log files
*/
@Override
public void handleError(ClientHttpResponse response) throws IOException {
try {
super.handleError(response);
} catch (HttpClientErrorException c) {
throw new HttpClientErrorException(c.getStatusCode(), c.getStatusText() + "\n" + prettyJson(c.getResponseBodyreplacedtring()), c.getResponseHeaders(), c.getResponseBodyAsByteArray(), this.getCharset(response));
} catch (HttpServerErrorException s) {
throw new HttpServerErrorException(s.getStatusCode(), s.getStatusText() + "\n" + prettyJson(s.getResponseBodyreplacedtring()), s.getResponseHeaders(), s.getResponseBodyAsByteArray(), this.getCharset(response));
} catch (UnknownHttpStatusCodeException u) {
throw new UnknownHttpStatusCodeException(u.getRawStatusCode(), u.getStatusText() + "\n" + prettyJson(u.getResponseBodyreplacedtring()), u.getResponseHeaders(), u.getResponseBodyAsByteArray(), this.getCharset(response));
}
}
18
Source : VndErrorResponseErrorHandler.java
with Apache License 2.0
from spring-cloud
with Apache License 2.0
from spring-cloud
@Override
public void handleError(ClientHttpResponse response) throws IOException {
VndErrors error = null;
try {
error = errorExtractor.extractData(response);
} catch (Exception e) {
super.handleError(response);
}
throw new DataFlowClientException(error);
}
18
Source : DefaultResponseErrorHandler.java
with Apache License 2.0
from SourceHot
with Apache License 2.0
from SourceHot
/**
* Handle the error in the given response with the given resolved status code.
* <p>The default implementation throws an {@link HttpClientErrorException}
* if the status code is {@link org.springframework.http.HttpStatus.Series#CLIENT_ERROR
* CLIENT_ERROR}, an {@link HttpServerErrorException} if it is
* {@link org.springframework.http.HttpStatus.Series#SERVER_ERROR SERVER_ERROR},
* or an {@link UnknownHttpStatusCodeException} in other cases.
* @since 5.0
* @see HttpClientErrorException#create
* @see HttpServerErrorException#create
*/
protected void handleError(ClientHttpResponse response, HttpStatus statusCode) throws IOException {
String statusText = response.getStatusText();
HttpHeaders headers = response.getHeaders();
byte[] body = getResponseBody(response);
Charset charset = getCharset(response);
String message = getErrorMessage(statusCode.value(), statusText, body, charset);
switch(statusCode.series()) {
case CLIENT_ERROR:
throw HttpClientErrorException.create(message, statusCode, statusText, headers, body, charset);
case SERVER_ERROR:
throw HttpServerErrorException.create(message, statusCode, statusText, headers, body, charset);
default:
throw new UnknownHttpStatusCodeException(message, statusCode.value(), statusText, headers, body, charset);
}
}
18
Source : SilentlyResponseErrorHandler.java
with Apache License 2.0
from penggle
with Apache License 2.0
from penggle
@Override
public void handleError(ClientHttpResponse response) throws IOException {
// nothing to do
}
18
Source : SilentlyResponseErrorHandler.java
with Apache License 2.0
from penggle
with Apache License 2.0
from penggle
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return false;
}
18
Source : ResultResponseErrorHandler.java
with Apache License 2.0
from penggle
with Apache License 2.0
from penggle
@Override
public void handleError(ClientHttpResponse response) throws IOException {
super.handleError(response);
}
18
Source : DynamicallyResponseErrorHandler.java
with Apache License 2.0
from penggle
with Apache License 2.0
from penggle
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return getResponseErrorHandler().hasError(response);
}
18
Source : DynamicallyResponseErrorHandler.java
with Apache License 2.0
from penggle
with Apache License 2.0
from penggle
@Override
public void handleError(ClientHttpResponse response) throws IOException {
getResponseErrorHandler().handleError(response);
}
18
Source : DefaultOAuth2ErrorResponseErrorHandler.java
with Apache License 2.0
from penggle
with Apache License 2.0
from penggle
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return this.defaultErrorHandler.hasError(response);
}
18
Source : RestTemplateResponseErrorHandler.java
with MIT License
from okanvk
with MIT License
from okanvk
@Override
public boolean hasError(ClientHttpResponse httpResponse) throws IOException {
return (httpResponse.getStatusCode().series() == HttpStatus.Series.CLIENT_ERROR || httpResponse.getStatusCode().series() == HttpStatus.Series.SERVER_ERROR);
}
18
Source : RestTemplateResponseErrorHandler.java
with MIT License
from okanvk
with MIT License
from okanvk
@SneakyThrows
@Override
public void handleError(ClientHttpResponse httpResponse) throws IOException {
if (httpResponse.getStatusCode().series() == HttpStatus.Series.CLIENT_ERROR) {
if (httpResponse.getStatusCode() == HttpStatus.UNAUTHORIZED) {
throw new SpotifyTokenExpiredException("Token Expired");
}
}
}
18
Source : RestTemplateXhrTransportTests.java
with MIT License
from mindcarver
with MIT License
from mindcarver
private ListenableFuture<WebSocketSession> connect(RestOperations restTemplate, ClientHttpResponse... responses) throws Exception {
RestTemplateXhrTransport transport = new RestTemplateXhrTransport(restTemplate);
transport.setTaskExecutor(new SyncTaskExecutor());
SockJsUrlInfo urlInfo = new SockJsUrlInfo(new URI("http://example.com"));
HttpHeaders headers = new HttpHeaders();
headers.add("h-foo", "h-bar");
TransportRequest request = new DefaultTransportRequest(urlInfo, headers, headers, transport, TransportType.XHR, CODEC);
return transport.connect(request, this.webSocketHandler);
}
18
Source : MessageBodyClientHttpResponseWrapper.java
with MIT License
from mindcarver
with MIT License
from mindcarver
/**
* Implementation of {@link ClientHttpResponse} that can not only check if
* the response has a message body, but also if its length is 0 (i.e. empty)
* by actually reading the input stream.
*
* @author Brian Clozel
* @since 4.1.5
* @see <a href="http://tools.ietf.org/html/rfc7230#section-3.3.3">RFC 7230 Section 3.3.3</a>
*/
clreplaced MessageBodyClientHttpResponseWrapper implements ClientHttpResponse {
private final ClientHttpResponse response;
@Nullable
private PushbackInputStream pushbackInputStream;
public MessageBodyClientHttpResponseWrapper(ClientHttpResponse response) throws IOException {
this.response = response;
}
/**
* Indicates whether the response has a message body.
* <p>Implementation returns {@code false} for:
* <ul>
* <li>a response status of {@code 1XX}, {@code 204} or {@code 304}</li>
* <li>a {@code Content-Length} header of {@code 0}</li>
* </ul>
* @return {@code true} if the response has a message body, {@code false} otherwise
* @throws IOException in case of I/O errors
*/
public boolean hasMessageBody() throws IOException {
HttpStatus status = HttpStatus.resolve(getRawStatusCode());
if (status != null && (status.is1xxInformational() || status == HttpStatus.NO_CONTENT || status == HttpStatus.NOT_MODIFIED)) {
return false;
}
if (getHeaders().getContentLength() == 0) {
return false;
}
return true;
}
/**
* Indicates whether the response has an empty message body.
* <p>Implementation tries to read the first bytes of the response stream:
* <ul>
* <li>if no bytes are available, the message body is empty</li>
* <li>otherwise it is not empty and the stream is reset to its start for further reading</li>
* </ul>
* @return {@code true} if the response has a zero-length message body, {@code false} otherwise
* @throws IOException in case of I/O errors
*/
@SuppressWarnings("ConstantConditions")
public boolean hasEmptyMessageBody() throws IOException {
InputStream body = this.response.getBody();
// Per contract body shouldn't be null, but check anyway..
if (body == null) {
return true;
}
if (body.markSupported()) {
body.mark(1);
if (body.read() == -1) {
return true;
} else {
body.reset();
return false;
}
} else {
this.pushbackInputStream = new PushbackInputStream(body);
int b = this.pushbackInputStream.read();
if (b == -1) {
return true;
} else {
this.pushbackInputStream.unread(b);
return false;
}
}
}
@Override
public HttpHeaders getHeaders() {
return this.response.getHeaders();
}
@Override
public InputStream getBody() throws IOException {
return (this.pushbackInputStream != null ? this.pushbackInputStream : this.response.getBody());
}
@Override
public HttpStatus getStatusCode() throws IOException {
return this.response.getStatusCode();
}
@Override
public int getRawStatusCode() throws IOException {
return this.response.getRawStatusCode();
}
@Override
public String getStatusText() throws IOException {
return this.response.getStatusText();
}
@Override
public void close() {
this.response.close();
}
}
18
Source : TransferRestErrorHandler.java
with MIT License
from mediatoolkit
with MIT License
from mediatoolkit
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return response.getStatusCode() != HttpStatus.OK;
}
18
Source : OpenRestResponseErrorHandler.java
with MIT License
from liuyadu
with MIT License
from liuyadu
@Override
public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
// false表示不管response的status是多少都返回没有错
return false;
}
18
Source : RestTemplateXhrTransportTests.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
private ClientHttpResponse response(HttpStatus status, String body) throws IOException {
ClientHttpResponse response = mock(ClientHttpResponse.clreplaced);
InputStream inputStream = getInputStream(body);
given(response.getStatusCode()).willReturn(status);
given(response.getBody()).willReturn(inputStream);
return response;
}
18
Source : MessageBodyClientHttpResponseWrapper.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
/**
* Implementation of {@link ClientHttpResponse} that can not only check if
* the response has a message body, but also if its length is 0 (i.e. empty)
* by actually reading the input stream.
*
* @author Brian Clozel
* @since 4.1.5
* @see <a href="http://tools.ietf.org/html/rfc7230#section-3.3.3">rfc7230 Section 3.3.3</a>
*/
clreplaced MessageBodyClientHttpResponseWrapper implements ClientHttpResponse {
private final ClientHttpResponse response;
private PushbackInputStream pushbackInputStream;
public MessageBodyClientHttpResponseWrapper(ClientHttpResponse response) throws IOException {
this.response = response;
}
/**
* Indicates whether the response has a message body.
* <p>Implementation returns {@code false} for:
* <ul>
* <li>a response status of {@code 1XX}, {@code 204} or {@code 304}</li>
* <li>a {@code Content-Length} header of {@code 0}</li>
* </ul>
* @return {@code true} if the response has a message body, {@code false} otherwise
* @throws IOException in case of I/O errors
*/
public boolean hasMessageBody() throws IOException {
HttpStatus responseStatus = this.getStatusCode();
if (responseStatus.is1xxInformational() || responseStatus == HttpStatus.NO_CONTENT || responseStatus == HttpStatus.NOT_MODIFIED) {
return false;
} else if (this.getHeaders().getContentLength() == 0) {
return false;
}
return true;
}
/**
* Indicates whether the response has an empty message body.
* <p>Implementation tries to read the first bytes of the response stream:
* <ul>
* <li>if no bytes are available, the message body is empty</li>
* <li>otherwise it is not empty and the stream is reset to its start for further reading</li>
* </ul>
* @return {@code true} if the response has a zero-length message body, {@code false} otherwise
* @throws IOException in case of I/O errors
*/
public boolean hasEmptyMessageBody() throws IOException {
InputStream body = this.response.getBody();
if (body == null) {
return true;
} else if (body.markSupported()) {
body.mark(1);
if (body.read() == -1) {
return true;
} else {
body.reset();
return false;
}
} else {
this.pushbackInputStream = new PushbackInputStream(body);
int b = this.pushbackInputStream.read();
if (b == -1) {
return true;
} else {
this.pushbackInputStream.unread(b);
return false;
}
}
}
@Override
public HttpHeaders getHeaders() {
return this.response.getHeaders();
}
@Override
public InputStream getBody() throws IOException {
return (this.pushbackInputStream != null ? this.pushbackInputStream : this.response.getBody());
}
@Override
public HttpStatus getStatusCode() throws IOException {
return this.response.getStatusCode();
}
@Override
public int getRawStatusCode() throws IOException {
return this.response.getRawStatusCode();
}
@Override
public String getStatusText() throws IOException {
return this.response.getStatusText();
}
@Override
public void close() {
this.response.close();
}
}
See More Examples