List of usage examples for org.springframework.http.client ClientHttpResponse getStatusCode
HttpStatus getStatusCode() throws IOException;
From source file:org.springframework.web.client.RestTemplate.java
private void logResponseStatus(HttpMethod method, URI url, ClientHttpResponse response) { if (Log.isLoggable(TAG, Log.DEBUG)) { try {/*from w ww. j a v a 2 s. c o m*/ Log.d(TAG, method.name() + " request for \"" + url + "\" resulted in " + response.getStatusCode() + " (" + response.getStatusText() + ")"); } catch (IOException e) { // ignore } } }
From source file:org.springframework.web.client.RestTemplate.java
private void handleResponseError(HttpMethod method, URI url, ClientHttpResponse response) throws IOException { if (Log.isLoggable(TAG, Log.WARN)) { try {//from ww w .ja va 2 s .c om Log.w(TAG, method.name() + " request for \"" + url + "\" resulted in " + response.getStatusCode() + " (" + response.getStatusText() + "); invoking error handler"); } catch (IOException e) { // ignore } } getErrorHandler().handleError(response); }
From source file:com.zhm.config.MyAuthorizationCodeAccessTokenProvider.java
public String obtainAuthorizationCode(OAuth2ProtectedResourceDetails details, AccessTokenRequest request) throws UserRedirectRequiredException, UserApprovalRequiredException, AccessDeniedException, OAuth2AccessDeniedException { AuthorizationCodeResourceDetails resource = (AuthorizationCodeResourceDetails) details; HttpHeaders headers = getHeadersForAuthorizationRequest(request); MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); if (request.containsKey(OAuth2Utils.USER_OAUTH_APPROVAL)) { form.set(OAuth2Utils.USER_OAUTH_APPROVAL, request.getFirst(OAuth2Utils.USER_OAUTH_APPROVAL)); for (String scope : details.getScope()) { form.set(scopePrefix + scope, request.getFirst(OAuth2Utils.USER_OAUTH_APPROVAL)); }/* w ww .j av a 2 s. com*/ } else { form.putAll(getParametersForAuthorizeRequest(resource, request)); } authorizationRequestEnhancer.enhance(request, resource, form, headers); final AccessTokenRequest copy = request; final ResponseExtractor<ResponseEntity<Void>> delegate = getAuthorizationResponseExtractor(); ResponseExtractor<ResponseEntity<Void>> extractor = new ResponseExtractor<ResponseEntity<Void>>() { @Override public ResponseEntity<Void> extractData(ClientHttpResponse response) throws IOException { if (response.getHeaders().containsKey("Set-Cookie")) { copy.setCookie(response.getHeaders().getFirst("Set-Cookie")); } return delegate.extractData(response); } }; // Instead of using restTemplate.exchange we use an explicit response extractor here so it can be overridden by // subclasses ResponseEntity<Void> response = getRestTemplate().execute(resource.getUserAuthorizationUri(), HttpMethod.POST, getRequestCallback(resource, form, headers), extractor, form.toSingleValueMap()); if (response.getStatusCode() == HttpStatus.OK) { // Need to re-submit with approval... throw getUserApprovalSignal(resource, request); } URI location = response.getHeaders().getLocation(); String query = location.getQuery(); Map<String, String> map = OAuth2Utils.extractMap(query); if (map.containsKey("state")) { request.setStateKey(map.get("state")); if (request.getPreservedState() == null) { String redirectUri = resource.getRedirectUri(request); if (redirectUri != null) { request.setPreservedState(redirectUri); } else { request.setPreservedState(new Object()); } } } String code = map.get("code"); if (code == null) { throw new UserRedirectRequiredException(location.toString(), form.toSingleValueMap()); } request.set("code", code); return code; }
From source file:org.fao.geonet.api.records.formatters.FormatterApi.java
private String getXmlFromUrl(ServiceContext context, String lang, String url, WebRequest request) throws IOException, URISyntaxException { String adjustedUrl = url;//from w w w. j a v a 2 s . c om if (!url.startsWith("http")) { adjustedUrl = context.getBean(SettingManager.class).getSiteURL(lang) + url; } else { final URI uri = new URI(url); Set allowedRemoteHosts = context.getApplicationContext().getBean("formatterRemoteFormatAllowedHosts", Set.class); Assert.isTrue(allowedRemoteHosts.contains(uri.getHost()), "xml.format is not allowed to make requests to " + uri.getHost()); } HttpUriRequest getXmlRequest = new HttpGet(adjustedUrl); final Iterator<String> headerNames = request.getHeaderNames(); while (headerNames.hasNext()) { String headerName = headerNames.next(); final String[] headers = request.getHeaderValues(headerName); for (String header : headers) { getXmlRequest.addHeader(headerName, header); } } GeonetHttpRequestFactory requestFactory = context.getBean(GeonetHttpRequestFactory.class); final ClientHttpResponse execute = requestFactory.execute(getXmlRequest); if (execute.getRawStatusCode() != 200) { throw new IllegalArgumentException("Request " + adjustedUrl + " did not succeed. Response Status: " + execute.getStatusCode() + ", status text: " + execute.getStatusText()); } return new String(ByteStreams.toByteArray(execute.getBody()), Constants.CHARSET); }
From source file:org.fao.geonet.util.XslUtil.java
/** * Returns the HTTP code or error message if error occurs during URL connection. * * @param url The URL to ckeck./*ww w . j ava 2 s.co m*/ * @param tryNumber the number of remaining tries. */ public static String getUrlStatus(String url, int tryNumber) { if (tryNumber < 1) { // protect against redirect loops return "ERR_TOO_MANY_REDIRECTS"; } HttpHead head = new HttpHead(url); GeonetHttpRequestFactory requestFactory = ApplicationContextHolder.get() .getBean(GeonetHttpRequestFactory.class); ClientHttpResponse response = null; try { response = requestFactory.execute(head, new Function<HttpClientBuilder, Void>() { @Nullable @Override public Void apply(@Nullable HttpClientBuilder originalConfig) { RequestConfig.Builder config = RequestConfig.custom().setConnectTimeout(1000) .setConnectionRequestTimeout(3000).setSocketTimeout(5000); RequestConfig requestConfig = config.build(); originalConfig.setDefaultRequestConfig(requestConfig); return null; } }); //response = requestFactory.execute(head); if (response.getRawStatusCode() == HttpStatus.SC_BAD_REQUEST || response.getRawStatusCode() == HttpStatus.SC_METHOD_NOT_ALLOWED || response.getRawStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) { // the website doesn't support HEAD requests. Need to do a GET... response.close(); HttpGet get = new HttpGet(url); response = requestFactory.execute(get); } if (response.getStatusCode().is3xxRedirection() && response.getHeaders().containsKey("Location")) { // follow the redirects return getUrlStatus(response.getHeaders().getFirst("Location"), tryNumber - 1); } return String.valueOf(response.getRawStatusCode()); } catch (IOException e) { Log.error(Geonet.GEONETWORK, "IOException validating " + url + " URL. " + e.getMessage(), e); return e.getMessage(); } finally { if (response != null) { response.close(); } } }
From source file:org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests.java
@Test public void cannotReadClassPathFiles() throws Exception { AbstractServletWebServerFactory factory = getFactory(); this.webServer = factory.getWebServer(exampleServletRegistration()); this.webServer.start(); ClientHttpResponse response = getClientResponse( getLocalUrl("/org/springframework/boot/SpringApplication.class")); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); }
From source file:org.cruk.genologics.api.impl.GenologicsAPIImpl.java
@Override public void downloadFile(Linkable<GenologicsFile> file, OutputStream resultStream) throws IOException { if (file == null) { throw new IllegalArgumentException("file cannot be null"); }//w w w.j av a 2 s . c om if (resultStream == null) { throw new IllegalArgumentException("resultStream cannot be null"); } GenologicsEntity entityAnno = checkEntityAnnotated(GenologicsFile.class); GenologicsFile realFile; if (file instanceof GenologicsFile) { realFile = (GenologicsFile) file; if (realFile.getContentLocation() == null) { // Don't know where the actual file is, so fetch to get the full info. realFile = retrieve(file.getUri(), GenologicsFile.class); } } else { realFile = retrieve(file.getUri(), GenologicsFile.class); } URI fileURL; if (downloadDirectFromHttpStore && HTTP_PROTOCOLS.contains(realFile.getContentLocation().getScheme())) { fileURL = realFile.getContentLocation(); } else { try { fileURL = new URI( getServerApiAddress() + entityAnno.uriSection() + "/" + realFile.getLimsid() + "/download"); } catch (URISyntaxException e) { throw new IllegalArgumentException( "File LIMS id " + realFile.getLimsid() + " produces an invalid URI for download.", e); } } logger.info("Downloading {}", fileURL); ClientHttpRequest request = httpRequestFactory.createRequest(fileURL, HttpMethod.GET); ClientHttpResponse response = request.execute(); switch (response.getStatusCode().series()) { case SUCCESSFUL: try (InputStream in = response.getBody()) { byte[] buffer = new byte[8192]; IOUtils.copyLarge(in, resultStream, buffer); } finally { resultStream.flush(); } logger.debug("{} download successful.", fileURL); break; default: logger.debug("{} download failed. HTTP {}", fileURL, response.getStatusCode()); throw new IOException("Could not download file " + realFile.getLimsid() + " (HTTP " + response.getStatusCode() + "): " + response.getStatusText()); } }
From source file:org.cloudfoundry.client.lib.rest.CloudControllerClientImpl.java
private String doGetFileByRange(String urlPath, Object app, String instance, String filePath, int start, int end, String range) { boolean supportsRanges; try {/*from w w w . j a va 2s . co m*/ supportsRanges = getRestTemplate().execute(getUrl(urlPath), HttpMethod.HEAD, new RequestCallback() { public void doWithRequest(ClientHttpRequest request) throws IOException { request.getHeaders().set("Range", "bytes=0-"); } }, new ResponseExtractor<Boolean>() { public Boolean extractData(ClientHttpResponse response) throws IOException { return response.getStatusCode().equals(HttpStatus.PARTIAL_CONTENT); } }, app, instance, filePath); } catch (CloudFoundryException e) { if (e.getStatusCode().equals(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE)) { // must be a 0 byte file return ""; } else { throw e; } } HttpHeaders headers = new HttpHeaders(); if (supportsRanges) { headers.set("Range", range); } HttpEntity<Object> requestEntity = new HttpEntity<Object>(headers); ResponseEntity<String> responseEntity = getRestTemplate().exchange(getUrl(urlPath), HttpMethod.GET, requestEntity, String.class, app, instance, filePath); String response = responseEntity.getBody(); boolean partialFile = false; if (responseEntity.getStatusCode().equals(HttpStatus.PARTIAL_CONTENT)) { partialFile = true; } if (!partialFile && response != null) { if (start == -1) { return response.substring(response.length() - end); } else { if (start >= response.length()) { if (response.length() == 0) { return ""; } throw new CloudFoundryException(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE, "The starting position " + start + " is past the end of the file content."); } if (end != -1) { if (end >= response.length()) { end = response.length() - 1; } return response.substring(start, end + 1); } else { return response.substring(start); } } } return response; }