Java Code Examples for org.springframework.http.client.ClientHttpRequest#execute()
The following examples show how to use
org.springframework.http.client.ClientHttpRequest#execute() .
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: OAuth2LoadBalancerClientAutoConfigurationTests.java From spring-cloud-security with Apache License 2.0 | 6 votes |
@Test public void userInfoLoadBalancedNoRetry() throws Exception { this.context = new SpringApplicationBuilder(ClientConfiguration.class) .properties("spring.config.name=test", "server.port=0", "spring.cloud.gateway.enabled=false", "security.oauth2.resource.userInfoUri:https://nosuchservice", "security.oauth2.resource.loadBalanced=true") .run(); assertThat( this.context.containsBean("loadBalancedUserInfoRestTemplateCustomizer")) .isTrue(); assertThat(this.context .containsBean("retryLoadBalancedUserInfoRestTemplateCustomizer")) .isFalse(); OAuth2RestTemplate template = this.context .getBean(UserInfoRestTemplateFactory.class).getUserInfoRestTemplate(); ClientHttpRequest request = template.getRequestFactory() .createRequest(new URI("https://nosuchservice"), HttpMethod.GET); expected.expectMessage("No instances available for nosuchservice"); request.execute(); }
Example 2
Source File: RestTemplate.java From spring-analysis-note with MIT License | 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} */ @Nullable protected <T> T doExecute(URI url, @Nullable HttpMethod method, @Nullable RequestCallback requestCallback, @Nullable ResponseExtractor<T> responseExtractor) throws RestClientException { Assert.notNull(url, "URI is required"); Assert.notNull(method, "HttpMethod is required"); ClientHttpResponse response = null; try { ClientHttpRequest request = createRequest(url, method); if (requestCallback != null) { requestCallback.doWithRequest(request); } response = request.execute(); handleResponse(url, method, response); return (responseExtractor != null ? responseExtractor.extractData(response) : 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 3
Source File: RestTemplate.java From java-technology-stack with MIT License | 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} */ @Nullable protected <T> T doExecute(URI url, @Nullable HttpMethod method, @Nullable RequestCallback requestCallback, @Nullable ResponseExtractor<T> responseExtractor) throws RestClientException { Assert.notNull(url, "URI is required"); Assert.notNull(method, "HttpMethod is required"); ClientHttpResponse response = null; try { ClientHttpRequest request = createRequest(url, method); if (requestCallback != null) { requestCallback.doWithRequest(request); } response = request.execute(); handleResponse(url, method, response); return (responseExtractor != null ? responseExtractor.extractData(response) : 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 4
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 5
Source File: RestTemplate.java From spring4-understanding with Apache License 2.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) { throw new ResourceAccessException("I/O error on " + method.name() + " request for \"" + url + "\": " + ex.getMessage(), ex); } finally { if (response != null) { response.close(); } } }
Example 6
Source File: TokenRefreshingClientHttpRequestFactory.java From google-plus-java-api with Apache License 2.0 | 5 votes |
public ClientHttpResponse execute() throws IOException { ClientHttpResponse response = delegate.execute(); if (response.getStatusCode() == HttpStatus.UNAUTHORIZED) { logger.info("Token is invalid (got 401 response). Trying get a new token using the refresh token"); String newToken = callback.refreshToken(); if (newToken == null) { return response; } else { logger.info("New token obtained, retrying the request with it"); // reflectively set the new token at the oauth2 interceptor (no nicer way, alas) for (ClientHttpRequestInterceptor interceptor: requestInterceptors) { if (interceptor.getClass().getName().equals("org.springframework.social.oauth2.OAuth2RequestInterceptor")) { Field field = ReflectionUtils.findField(interceptor.getClass(), "accessToken"); field.setAccessible(true); ReflectionUtils.setField(field, interceptor, newToken); } } // create a new request, using the new token, but don't go through the refreshing factory again // because it may cause an endless loop if all tokens are invalid ClientHttpRequest newRequest = TokenRefreshingClientHttpRequestFactory.this.delegate.createRequest(delegate.getURI(), delegate.getMethod()); return newRequest.execute(); } } return response; }
Example 7
Source File: ClientFactoryHelper.java From jwala with Apache License 2.0 | 4 votes |
public ClientHttpResponse requestGet(URI statusUri) throws IOException { ClientHttpRequest request = httpClientFactory.createRequest(statusUri, HttpMethod.GET); return request.execute(); }
Example 8
Source File: WebServerStateSetterWorker.java From jwala with Apache License 2.0 | 4 votes |
/** * Ping the web server via http get. * * @param webServer the web server to ping. */ @Async("webServerTaskExecutor") public void pingWebServer(final WebServer webServer) { if (!webServerCanBePinged(webServer)) { return; } synchronized (webServersToPing) { if (webServersToPing.contains(webServer.getId())) { LOGGER.debug("List of web servers currently being pinged: {}", webServersToPing); LOGGER.debug("Cannot ping web server {} since it is currently being pinged", webServer.getName(), webServer); return; } webServersToPing.add(webServer.getId()); } LOGGER.debug("Requesting {} for web server {}", webServer.getStatusUri(), webServer.getName()); ClientHttpResponse response = null; try { final ClientHttpRequest request; request = httpRequestFactory.createRequest(webServer.getStatusUri(), HttpMethod.GET); response = request.execute(); LOGGER.debug("Web server {} status code = {}", webServer.getName(), response.getStatusCode()); if (HttpStatus.OK.equals(response.getStatusCode())) { setState(webServer, WebServerReachableState.WS_REACHABLE, StringUtils.EMPTY); } else { setState(webServer, WebServerReachableState.WS_UNREACHABLE, MessageFormat.format(RESPONSE_NOT_OK_MSG, webServer.getStatusUri(), response.getStatusCode())); } } catch (final IOException e) { if (!WebServerReachableState.WS_UNREACHABLE.equals(webServer.getState())) { LOGGER.warn("Failed to ping {}!", webServer.getName(), e); setState(webServer, WebServerReachableState.WS_UNREACHABLE, StringUtils.EMPTY); } } finally { if (response != null) { response.close(); } webServersToPing.remove(webServer.getId()); } }
Example 9
Source File: PostmanTestStepsRunner.java From microcks with Apache License 2.0 | 4 votes |
@Override public List<TestReturn> runTest(Service service, Operation operation, TestResult testResult, List<Request> requests, String endpointUrl, HttpMethod method) throws URISyntaxException, IOException { if (log. isDebugEnabled()){ log.debug("Launching test run on " + endpointUrl + " for " + requests.size() + " request(s)"); } if (endpointUrl.endsWith("/")) { endpointUrl = endpointUrl.substring(0, endpointUrl.length() - 1); } // Microcks-postman-runner interface object building. JsonNode jsonArg = mapper.createObjectNode(); ((ObjectNode) jsonArg).put("operation", operation.getName()); ((ObjectNode) jsonArg).put("callbackUrl", testsCallbackUrl + "/api/tests/" + testResult.getId() + "/testCaseResult"); // First we have to retrieved and add the test script for this operation from within Postman collection. JsonNode testScript = extractOperationTestScript(operation); if (testScript != null) { log.debug("Found a testScript for this operation !"); ((ObjectNode) jsonArg).set("testScript", testScript); } // Then we have to add the corresponding 'requests' objects. ArrayNode jsonRequests = mapper.createArrayNode(); for (Request request : requests) { JsonNode jsonRequest = mapper.createObjectNode(); String operationName = operation.getName().substring(operation.getName().indexOf(" ") + 1); String customizedEndpointUrl = endpointUrl + URIBuilder.buildURIFromPattern(operationName, request.getQueryParameters()); log.debug("Using customized endpoint url: " + customizedEndpointUrl); ((ObjectNode) jsonRequest).put("endpointUrl", customizedEndpointUrl); ((ObjectNode) jsonRequest).put("method", operation.getMethod()); ((ObjectNode) jsonRequest).put("name", request.getName()); if (request.getContent() != null && request.getContent().length() > 0) { ((ObjectNode) jsonRequest).put("body", request.getContent()); } if (request.getQueryParameters() != null && request.getQueryParameters().size() > 0) { ArrayNode jsonParams = buildQueryParams(request.getQueryParameters()); ((ObjectNode) jsonRequest).set("queryParams", jsonParams); } // Set headers to request if any. Start with those coming from request itself. // Add or override existing headers with test specific ones for operation and globals. Set<Header> headers = new HashSet<>(); if (request.getHeaders() != null) { headers.addAll(request.getHeaders()); } if (testResult.getOperationsHeaders() != null) { if (testResult.getOperationsHeaders().getGlobals() != null) { headers.addAll(testResult.getOperationsHeaders().getGlobals()); } if (testResult.getOperationsHeaders().get(operation.getName()) != null) { headers.addAll(testResult.getOperationsHeaders().get(operation.getName())); } } if (headers != null && headers.size() > 0) { ArrayNode jsonHeaders = buildHeaders(headers); ((ObjectNode) jsonRequest).set("headers", jsonHeaders); } jsonRequests.add(jsonRequest); } ((ObjectNode) jsonArg).set("requests", jsonRequests); URI postmanRunnerURI = new URI(postmanRunnerUrl + "/tests/" + testResult.getId()); ClientHttpRequest httpRequest = clientHttpRequestFactory.createRequest(postmanRunnerURI, HttpMethod.POST); httpRequest.getBody().write(mapper.writeValueAsBytes(jsonArg)); httpRequest.getHeaders().add("Content-Type", "application/json"); // Actually execute request. ClientHttpResponse httpResponse = null; try{ httpResponse = httpRequest.execute(); } catch (IOException ioe){ log.error("IOException while executing request ", ioe); } finally { if (httpResponse != null) { httpResponse.close(); } } return new ArrayList<TestReturn>(); }
Example 10
Source File: HttpTestRunner.java From microcks with Apache License 2.0 | 4 votes |
@Override public List<TestReturn> runTest(Service service, Operation operation, TestResult testResult, List<Request> requests, String endpointUrl, HttpMethod method) throws URISyntaxException, IOException{ if (log. isDebugEnabled()){ log.debug("Launching test run on " + endpointUrl + " for " + requests.size() + " request(s)"); } if (requests.isEmpty()) { return null; } // Initialize result container. List<TestReturn> result = new ArrayList<TestReturn>(); for (Request request : requests){ // Reset status code, message and request each time. int code = TestReturn.SUCCESS_CODE; String message = null; String customizedEndpointUrl = endpointUrl; if (service.getType().equals(ServiceType.REST)){ String operationName = operation.getName(); // Name may start with verb, remove it if present. if (operationName.indexOf(' ') > 0 && operationName.indexOf(' ') < operationName.length()) { operationName = operationName.split(" ")[1]; } customizedEndpointUrl += URIBuilder.buildURIFromPattern(operationName, request.getQueryParameters()); log.debug("Using customized endpoint url: " + customizedEndpointUrl); } ClientHttpRequest httpRequest = clientHttpRequestFactory.createRequest(new URI(customizedEndpointUrl), method); // Set headers to request if any. Start with those coming from request itself. // Add or override existing headers with test specific ones for operation and globals. Set<Header> headers = new HashSet<>(); if (request.getHeaders() != null) { headers.addAll(request.getHeaders()); } if (testResult.getOperationsHeaders() != null) { if (testResult.getOperationsHeaders().getGlobals() != null) { headers.addAll(testResult.getOperationsHeaders().getGlobals()); } if (testResult.getOperationsHeaders().get(operation.getName()) != null) { headers.addAll(testResult.getOperationsHeaders().get(operation.getName())); } } if (headers.size() > 0){ for (Header header : headers){ log.debug("Adding header " + header.getName() + " to request"); httpRequest.getHeaders().add(header.getName(), buildValue(header.getValues())); } // Update request headers for traceability of possibly added ones. request.setHeaders(headers); } // If there's input content, add it to request. if (request.getContent() != null) { httpRequest.getBody().write(request.getContent().getBytes()); } // Actually execute request. long startTime = System.currentTimeMillis(); ClientHttpResponse httpResponse = null; try{ httpResponse = httpRequest.execute(); } catch (IOException ioe){ log.error("IOException while executing request " + request.getName() + " on " + endpointUrl, ioe); code = TestReturn.FAILURE_CODE; message = ioe.getMessage(); } long duration = System.currentTimeMillis() - startTime; // Extract and store response body so that stream may not be consumed more than o1 time ;-) String responseContent = null; if (httpResponse != null){ StringWriter writer = new StringWriter(); IOUtils.copy(httpResponse.getBody(), writer); responseContent = writer.toString(); } // If still in success, check if http code is out of correct ranges (20x and 30x). if (code == TestReturn.SUCCESS_CODE){ code = extractTestReturnCode(service, operation, request, httpResponse, responseContent); message = extractTestReturnMessage(service, operation, request, httpResponse); } // Create a Response object for returning. Response response = new Response(); if (httpResponse != null){ response.setContent(responseContent); response.setStatus(String.valueOf(httpResponse.getRawStatusCode())); response.setMediaType(httpResponse.getHeaders().getContentType().toString()); headers = buildHeaders(httpResponse); if (headers != null){ response.setHeaders(headers); } httpResponse.close(); } result.add(new TestReturn(code, duration, message, request, response)); } return result; }
Example 11
Source File: RestHttpClientFactory.java From website with GNU Affero General Public License v3.0 | 4 votes |
public static ClientHttpResponse execute(String relativeUrl, HttpMethod method) throws IOException { ClientHttpRequest request = newInstance(relativeUrl, method); return request.execute(); }