org.springframework.http.client.ClientHttpResponse Java Examples
The following examples show how to use
org.springframework.http.client.ClientHttpResponse.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RetryLoadBalancerInterceptorTest.java From spring-cloud-commons with Apache License 2.0 | 7 votes |
@Test public void interceptNeverRetry() throws Throwable { HttpRequest request = mock(HttpRequest.class); when(request.getURI()).thenReturn(new URI("http://foo")); ClientHttpResponse clientHttpResponse = new MockClientHttpResponse(new byte[] {}, HttpStatus.OK); ServiceInstance serviceInstance = mock(ServiceInstance.class); when(this.client.choose(eq("foo"))).thenReturn(serviceInstance); when(this.client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class))).thenReturn(clientHttpResponse); when(this.lbRequestFactory.createRequest(any(), any(), any())) .thenReturn(mock(LoadBalancerRequest.class)); this.lbProperties.setEnabled(true); RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor( this.client, this.lbProperties, this.lbRequestFactory, this.loadBalancedRetryFactory); byte[] body = new byte[] {}; ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); interceptor.intercept(request, body, execution); verify(this.lbRequestFactory).createRequest(request, body, execution); }
Example #2
Source File: TransactionClientHttpRequestInterceptor.java From txle with Apache License 2.0 | 7 votes |
@Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { if (omegaContext != null && omegaContext.globalTxId() != null) { request.getHeaders().add(GLOBAL_TX_ID_KEY, omegaContext.globalTxId()); request.getHeaders().add(LOCAL_TX_ID_KEY, omegaContext.localTxId()); request.getHeaders().add(GLOBAL_TX_CATEGORY_KEY, omegaContext.category()); LOG.debug("Added {} {} and {} {} to request header", GLOBAL_TX_ID_KEY, omegaContext.globalTxId(), LOCAL_TX_ID_KEY, omegaContext.localTxId(), GLOBAL_TX_CATEGORY_KEY, omegaContext.category()); } return execution.execute(request, body); }
Example #3
Source File: RetryLoadBalancerInterceptorTest.java From spring-cloud-commons with Apache License 2.0 | 6 votes |
@Test public void interceptSuccess() throws Throwable { HttpRequest request = mock(HttpRequest.class); when(request.getURI()).thenReturn(new URI("http://foo")); ClientHttpResponse clientHttpResponse = new MockClientHttpResponse(new byte[] {}, HttpStatus.OK); LoadBalancedRetryPolicy policy = mock(LoadBalancedRetryPolicy.class); ServiceInstance serviceInstance = mock(ServiceInstance.class); when(this.client.choose(eq("foo"))).thenReturn(serviceInstance); when(this.client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class))).thenReturn(clientHttpResponse); when(this.lbRequestFactory.createRequest(any(), any(), any())) .thenReturn(mock(LoadBalancerRequest.class)); this.lbProperties.setEnabled(true); RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor( this.client, this.lbProperties, this.lbRequestFactory, new MyLoadBalancedRetryFactory(policy)); byte[] body = new byte[] {}; ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); ClientHttpResponse rsp = interceptor.intercept(request, body, execution); then(rsp).isEqualTo(clientHttpResponse); verify(this.lbRequestFactory).createRequest(request, body, execution); }
Example #4
Source File: WingtipsClientHttpRequestInterceptor.java From wingtips with Apache License 2.0 | 6 votes |
/** * Constructor that lets you choose whether downstream calls will be surrounded with a subspan and supply the relevant tag strategy * for the subspan. * * @param surroundCallsWithSubspan pass in true to have downstream calls surrounded with a new span, false to only * propagate the current span's info downstream (no subspan). * @param tagAndNamingStrategy The span tag and naming strategy to use - cannot be null. If you really want no * tag and naming strategy, then pass in {@link NoOpHttpTagStrategy#getDefaultInstance()}. * @param tagAndNamingAdapter The tag and naming adapter to use - cannot be null. If you really want no tag and * naming adapter, then pass in {@link NoOpHttpTagAdapter#getDefaultInstance()}. */ public WingtipsClientHttpRequestInterceptor( boolean surroundCallsWithSubspan, HttpTagAndSpanNamingStrategy<HttpRequest, ClientHttpResponse> tagAndNamingStrategy, HttpTagAndSpanNamingAdapter<HttpRequest, ClientHttpResponse> tagAndNamingAdapter ) { if (tagAndNamingStrategy == null) { throw new IllegalArgumentException( "tagAndNamingStrategy cannot be null - if you really want no strategy, use NoOpHttpTagStrategy" ); } if (tagAndNamingAdapter == null) { throw new IllegalArgumentException( "tagAndNamingAdapter cannot be null - if you really want no adapter, use NoOpHttpTagAdapter" ); } this.surroundCallsWithSubspan = surroundCallsWithSubspan; this.tagAndNamingStrategy = tagAndNamingStrategy; this.tagAndNamingAdapter = tagAndNamingAdapter; }
Example #5
Source File: CompensableRequestInterceptor.java From ByteTCC with GNU Lesser General Public License v3.0 | 6 votes |
private void invokeAfterRecvResponse(ClientHttpResponse httpResponse, boolean serverFlag) throws IOException { SpringCloudBeanRegistry beanRegistry = SpringCloudBeanRegistry.getInstance(); CompensableBeanFactory beanFactory = beanRegistry.getBeanFactory(); TransactionInterceptor transactionInterceptor = beanFactory.getTransactionInterceptor(); HttpHeaders respHeaders = httpResponse.getHeaders(); String respTransactionStr = respHeaders.getFirst(HEADER_TRANCACTION_KEY); String respPropagationStr = respHeaders.getFirst(HEADER_PROPAGATION_KEY); String respRecursivelyStr = respHeaders.getFirst(HEADER_RECURSIVELY_KEY); String transactionText = StringUtils.trimToNull(respTransactionStr); byte[] byteArray = StringUtils.isBlank(transactionText) ? null : Base64.getDecoder().decode(transactionText); TransactionContext serverContext = byteArray == null || byteArray.length == 0 // ? null : (TransactionContext) SerializeUtils.deserializeObject(byteArray); TransactionResponseImpl txResp = new TransactionResponseImpl(); txResp.setTransactionContext(serverContext); RemoteCoordinator serverCoordinator = beanRegistry.getConsumeCoordinator(respPropagationStr); txResp.setSourceTransactionCoordinator(serverCoordinator); txResp.setParticipantDelistFlag(serverFlag ? StringUtils.equalsIgnoreCase(respRecursivelyStr, "TRUE") : true); transactionInterceptor.afterReceiveResponse(txResp); }
Example #6
Source File: WingtipsSpringUtil.java From wingtips with Apache License 2.0 | 6 votes |
/** * @param tagAndNamingStrategy The span tag and naming strategy to use - cannot be null. If you really want no * tag and naming strategy, then pass in {@link NoOpHttpTagStrategy#getDefaultInstance()}. * @param tagAndNamingAdapter The tag and naming adapter to use - cannot be null. If you really want no tag and * naming adapter, then pass in {@link NoOpHttpTagAdapter#getDefaultInstance()}. * @return A new {@link RestTemplate} instance with a {@link WingtipsClientHttpRequestInterceptor} * already added, and with the subspan option and tag/naming strategy and adapter set to the given arguments. */ public static RestTemplate createTracingEnabledRestTemplate( boolean surroundCallsWithSubspan, HttpTagAndSpanNamingStrategy<HttpRequest, ClientHttpResponse> tagAndNamingStrategy, HttpTagAndSpanNamingAdapter<HttpRequest, ClientHttpResponse> tagAndNamingAdapter ) { RestTemplate restTemplate = new RestTemplate(); restTemplate.getInterceptors().add( new WingtipsClientHttpRequestInterceptor( surroundCallsWithSubspan, tagAndNamingStrategy, tagAndNamingAdapter ) ); return restTemplate; }
Example #7
Source File: MockRestServiceServer.java From spring-analysis-note with MIT License | 6 votes |
private org.springframework.mock.http.client.MockAsyncClientHttpRequest createRequestInternal( URI uri, HttpMethod method) { Assert.notNull(uri, "'uri' must not be null"); Assert.notNull(method, "'httpMethod' must not be null"); return new org.springframework.mock.http.client.MockAsyncClientHttpRequest(method, uri) { @Override protected ClientHttpResponse executeInternal() throws IOException { ClientHttpResponse response = expectationManager.validateRequest(this); setResponse(response); return response; } }; }
Example #8
Source File: TransactionClientHttpRequestInterceptor.java From servicecomb-pack with Apache License 2.0 | 6 votes |
@Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { if (omegaContext!= null && omegaContext.globalTxId() != null) { request.getHeaders().add(GLOBAL_TX_ID_KEY, omegaContext.globalTxId()); request.getHeaders().add(LOCAL_TX_ID_KEY, omegaContext.localTxId()); LOG.debug("Added {} {} and {} {} to request header", GLOBAL_TX_ID_KEY, omegaContext.globalTxId(), LOCAL_TX_ID_KEY, omegaContext.localTxId()); } else { LOG.debug("Cannot inject transaction ID, as the OmegaContext is null or cannot get the globalTxId."); } return execution.execute(request, body); }
Example #9
Source File: AsyncRestTemplateIntegrationTests.java From spring-analysis-note with MIT License | 6 votes |
@Override public ListenableFuture<ClientHttpResponse> intercept(HttpRequest request, byte[] body, org.springframework.http.client.AsyncClientHttpRequestExecution execution) throws IOException { ListenableFuture<ClientHttpResponse> future = execution.executeAsync(request, body); future.addCallback( resp -> { response = resp; this.latch.countDown(); }, ex -> { exception = ex; this.latch.countDown(); }); return future; }
Example #10
Source File: DCTMJaxbErrorHandler.java From documentum-rest-client-java with Apache License 2.0 | 6 votes |
@SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void handleError(ClientHttpResponse response) throws IOException { MediaType mediaType = response.getHeaders().getContentType(); RestError error = null; for(HttpMessageConverter converter : converters) { if(converter.canRead(JaxbRestError.class, mediaType)) { try { error = (RestError)converter.read(JaxbRestError.class, response); } catch(Exception e) { error = new JaxbRestError(); ((JaxbRestError)error).setStatus(response.getRawStatusCode()); } break; } } throw new DCTMRestErrorException(response.getHeaders(), response.getStatusCode(), error); }
Example #11
Source File: AsyncRestTemplate.java From java-technology-stack with MIT License | 6 votes |
@Override @Nullable protected final T adapt(ClientHttpResponse response) throws ExecutionException { try { if (!getErrorHandler().hasError(response)) { logResponseStatus(this.method, this.url, response); } else { handleResponseError(this.method, this.url, response); } return convertResponse(response); } catch (Throwable ex) { throw new ExecutionException(ex); } finally { response.close(); } }
Example #12
Source File: RestTemplateXhrTransportTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void connectReceiveAndCloseWithStompFrame() throws Exception { StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND); accessor.setDestination("/destination"); MessageHeaders headers = accessor.getMessageHeaders(); Message<byte[]> message = MessageBuilder.createMessage("body".getBytes(StandardCharsets.UTF_8), headers); byte[] bytes = new StompEncoder().encode(message); TextMessage textMessage = new TextMessage(bytes); SockJsFrame frame = SockJsFrame.messageFrame(new Jackson2SockJsMessageCodec(), textMessage.getPayload()); String body = "o\n" + frame.getContent() + "\n" + "c[3000,\"Go away!\"]"; ClientHttpResponse response = response(HttpStatus.OK, body); connect(response); verify(this.webSocketHandler).afterConnectionEstablished(any()); verify(this.webSocketHandler).handleMessage(any(), eq(textMessage)); verify(this.webSocketHandler).afterConnectionClosed(any(), eq(new CloseStatus(3000, "Go away!"))); verifyNoMoreInteractions(this.webSocketHandler); }
Example #13
Source File: CloudControllerResponseErrorHandler.java From cf-java-client-sap with Apache License 2.0 | 5 votes |
@Override public void handleError(ClientHttpResponse response) throws IOException { HttpStatus statusCode = response.getStatusCode(); switch (statusCode.series()) { case CLIENT_ERROR: case SERVER_ERROR: throw getException(response); default: throw new RestClientException("Unknown status code [" + statusCode + "]"); } }
Example #14
Source File: RestTemplate.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Execute the given method on the provided URI. * <p>The {@link ClientHttpRequest} is processed using the {@link RequestCallback}; * the response with the {@link ResponseExtractor}. * @param url the fully-expanded URL to connect to * @param method the HTTP method to execute (GET, POST, etc.) * @param requestCallback object that prepares the request (can be {@code null}) * @param responseExtractor object that extracts the return value from the response (can be {@code null}) * @return an arbitrary object, as returned by the {@link ResponseExtractor} */ protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { Assert.notNull(url, "'url' must not be null"); Assert.notNull(method, "'method' must not be null"); ClientHttpResponse response = null; try { ClientHttpRequest request = createRequest(url, method); if (requestCallback != null) { requestCallback.doWithRequest(request); } response = request.execute(); handleResponse(url, method, response); if (responseExtractor != null) { return responseExtractor.extractData(response); } else { return null; } } catch (IOException ex) { String resource = url.toString(); String query = url.getRawQuery(); resource = (query != null ? resource.substring(0, resource.indexOf('?')) : resource); throw new ResourceAccessException("I/O error on " + method.name() + " request for \"" + resource + "\": " + ex.getMessage(), ex); } finally { if (response != null) { response.close(); } } }
Example #15
Source File: NonBlockingIO.java From riptide with MIT License | 5 votes |
@Override public CompletableFuture<ClientHttpResponse> execute(final RequestArguments arguments) throws IOException { final URI uri = arguments.getRequestUri(); final HttpMethod method = arguments.getMethod(); final AsyncClientHttpRequest request = requestFactory.createAsyncRequest(uri, method); copyTo(arguments.getHeaders(), request.getHeaders()); arguments.getEntity().writeTo(request); return toCompletable(request.executeAsync()); }
Example #16
Source File: LoggingInterceptor.java From camunda-bpm-platform with Apache License 2.0 | 5 votes |
@Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { log(request); try { ClientHttpResponse response = execution.execute(request, body); log(response); return response; } catch (IOException e) { log.error("Request execution failed:"); e.printStackTrace(); throw e; } }
Example #17
Source File: ScmPropertySourceLocator.java From super-cloudops with Apache License 2.0 | 5 votes |
@Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { for (Entry<String, String> h : headers.entrySet()) { request.getHeaders().add(h.getKey(), h.getValue()); } return execution.execute(request, body); }
Example #18
Source File: JsonRpcResponseErrorHandler.java From jsonrpc4j with MIT License | 5 votes |
private HttpStatus getHttpStatusCode(ClientHttpResponse response) throws IOException { final HttpStatus statusCode; try { statusCode = response.getStatusCode(); } catch (IllegalArgumentException ex) { throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(), response.getHeaders(), getResponseBody(response), getCharset(response)); } return statusCode; }
Example #19
Source File: TracingClientHttpRequestInterceptor.java From brave with Apache License 2.0 | 5 votes |
@Override public ClientHttpResponse intercept(HttpRequest req, byte[] body, ClientHttpRequestExecution execution) throws IOException { HttpRequestWrapper request = new HttpRequestWrapper(req); Span span = handler.handleSend(request); ClientHttpResponse response = null; Throwable error = null; try (Scope ws = currentTraceContext.newScope(span.context())) { return response = execution.execute(req, body); } catch (Throwable e) { error = e; throw e; } finally { handler.handleReceive(new ClientHttpResponseWrapper(request, response, error), span); } }
Example #20
Source File: CredHubRestTemplateFactory.java From spring-credhub with Apache License 2.0 | 5 votes |
@Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { HttpRequestWrapper requestWrapper = new HttpRequestWrapper(request); HttpHeaders headers = requestWrapper.getHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_JSON); return execution.execute(requestWrapper, body); }
Example #21
Source File: Requester.java From riptide with MIT License | 5 votes |
@Override public CompletableFuture<ClientHttpResponse> call(final Route route) { final RequestExecution execution = plugins.aroundAsync( plugins.aroundDispatch( plugins.aroundSerialization( plugins.aroundNetwork( network)))); return throwingFunction(execution::execute).apply(arguments.withRoute(route)); }
Example #22
Source File: WechatErrorHandler.java From spring-social-wechat with Apache License 2.0 | 5 votes |
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(); } }
Example #23
Source File: RestClientResponseErrorHandlerTest.java From sinavi-jfw with Apache License 2.0 | 5 votes |
@Before public void setup() { handler = new RestClientResponseErrorHandler(); response = mock(ClientHttpResponse.class); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", "application/json"); when(response.getHeaders()).thenReturn(headers); }
Example #24
Source File: WingtipsSpringUtilTest.java From wingtips with Apache License 2.0 | 5 votes |
NullConstructorArgsScenario( HttpTagAndSpanNamingStrategy<HttpRequest, ClientHttpResponse> strategy, HttpTagAndSpanNamingAdapter<HttpRequest, ClientHttpResponse> adapter, String expectedExceptionMessage ) { this.strategy = strategy; this.adapter = adapter; this.expectedExceptionMessage = expectedExceptionMessage; }
Example #25
Source File: ErrorKindTagGenerator.java From riptide with MIT License | 5 votes |
@Override public Iterable<Tag> onResponse( final RequestArguments arguments, final ClientHttpResponse response) { return NONE; }
Example #26
Source File: ApiFallbackProvider.java From springcloud-course with GNU General Public License v3.0 | 5 votes |
public ClientHttpResponse fallbackResponse(String message) { return new ClientHttpResponse() { @Override public HttpStatus getStatusCode() throws IOException { return HttpStatus.OK; } @Override public int getRawStatusCode() throws IOException { return 200; } @Override public String getStatusText() throws IOException { return "OK"; } @Override public void close() { } @Override public InputStream getBody() throws IOException { String bodyText = String.format("{\"code\": 999,\"message\": \"Service unavailable:%s\"}", message); return new ByteArrayInputStream(bodyText.getBytes()); } @Override public HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return headers; } }; }
Example #27
Source File: BasicAuthorizationInterceptor.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { String token = Base64Utils.encodeToString((this.username + ":" + this.password).getBytes(UTF_8)); request.getHeaders().add("Authorization", "Basic " + token); return execution.execute(request, body); }
Example #28
Source File: MockMvcClientHttpRequestFactory.java From java-technology-stack with MIT License | 5 votes |
@Override public ClientHttpRequest createRequest(final URI uri, final HttpMethod httpMethod) { return new MockClientHttpRequest(httpMethod, uri) { @Override public ClientHttpResponse executeInternal() throws IOException { return getClientHttpResponse(httpMethod, uri, getHeaders(), getBodyAsBytes()); } }; }
Example #29
Source File: SmartlingClientConfiguration.java From mojito with Apache License 2.0 | 5 votes |
public OAuth2RestTemplate smartlingRestTemplate() { OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(smartling(), new DefaultOAuth2ClientContext()); RestTemplateUtils restTemplateUtils = new RestTemplateUtils(); restTemplateUtils.enableFeature(oAuth2RestTemplate, DeserializationFeature.UNWRAP_ROOT_VALUE); AccessTokenProviderChain accessTokenProviderChain = new AccessTokenProviderChain(Arrays.asList( new SmartlingAuthorizationCodeAccessTokenProvider()) ); oAuth2RestTemplate.setAccessTokenProvider(accessTokenProviderChain); DefaultUriTemplateHandler defaultUriTemplateHandler = new DefaultUriTemplateHandler(); defaultUriTemplateHandler.setBaseUrl(baseUri); oAuth2RestTemplate.setUriTemplateHandler(defaultUriTemplateHandler); oAuth2RestTemplate.setErrorHandler(new DefaultResponseErrorHandler() { @Override public void handleError(ClientHttpResponse response) throws IOException { try { super.handleError(response); } catch (HttpClientErrorException e) { if (resttemplateLogger.isDebugEnabled()) { resttemplateLogger.debug(e.getResponseBodyAsString()); } throw e; } } }); return oAuth2RestTemplate; }
Example #30
Source File: ExtractingResponseErrorHandler.java From java-technology-stack with MIT License | 5 votes |
private void extract(@Nullable Class<? extends RestClientException> exceptionClass, ClientHttpResponse response) throws IOException { if (exceptionClass == null) { return; } HttpMessageConverterExtractor<? extends RestClientException> extractor = new HttpMessageConverterExtractor<>(exceptionClass, this.messageConverters); RestClientException exception = extractor.extractData(response); if (exception != null) { throw exception; } }