List of usage examples for org.springframework.http.client ClientHttpResponse getHeaders
HttpHeaders getHeaders();
From source file:cz.jirutka.spring.http.client.cache.DefaultCachingPolicy.java
protected boolean isResponseCacheable(ClientHttpResponse response) { boolean cacheable = false; HttpHeaders headers = response.getHeaders(); try {/* w w w.jav a2 s .c om*/ int status = response.getRawStatusCode(); if (isImplicitlyCacheableStatus(status)) { cacheable = true; //MAY be cached } else if (isUncacheableStatus(status)) { log.trace("Response with status code {} is not cacheable", status); return false; } } catch (IOException ex) { throw new IllegalStateException(ex); } if (isExplicitlyNonCacheable(response)) { log.trace("Response with Cache-Control: '{}' is not cacheable", headers.getCacheControl()); return false; } if (headers.getContentLength() > maxBodySizeBytes) { log.debug("Response with Content-Lenght {} > {} is not cacheable", headers.getContentLength(), maxBodySizeBytes); return false; } try { if (response.getHeaders().getDate() < 0) { log.debug("Response without a valid Date header is not cacheable"); return false; } } catch (IllegalArgumentException ex) { return false; } // dunno how to properly handle Vary if (headers.containsKey("Vary")) { log.trace("Response with Vary header is not cacheable"); return false; } return (cacheable || isExplicitlyCacheable(response)); }
From source file:cz.jirutka.spring.http.client.cache.DefaultCachingPolicy.java
public boolean isResponseCacheable(HttpRequest request, ClientHttpResponse response) { HttpHeaders reqHeaders = request.getHeaders(); HttpHeaders respHeaders = response.getHeaders(); if (!isCacheableMethod(request.getMethod())) { log.trace("Not cacheable: method {}", request.getMethod()); return false; }//from ww w .j a va 2s . co m if (parseCacheControl(reqHeaders).isNoStore()) { log.trace("Not cacheable: request has Cache-Control: no-store"); return false; } if (sharedCache) { if (reqHeaders.getFirst("Authorization") != null) { CacheControl cc = parseCacheControl(respHeaders); if (!cc.isPublic() && cc.getSMaxAge() <= 0) { log.trace("Not cacheable: this cache is shared and request contains " + "Authorization header, but no Cache-Control: public"); return false; } } } return isResponseCacheable(response); }
From source file:org.zalando.riptide.ActionsTest.java
@Test public void shouldNormalizeLocationAndContentLocation() { final HttpHeaders headers = new HttpHeaders(); headers.setLocation(URI.create("/accounts/456")); headers.set(CONTENT_LOCATION, "/accounts/456"); server.expect(requestTo(url)).andRespond(withSuccess().headers(headers)); final ClientHttpResponse response = unit.execute(GET, url) .dispatch(series(), on(SUCCESSFUL).map(normalize(url)).capture()).to(ClientHttpResponse.class); assertThat(response.getHeaders().getLocation(), hasToString("https://api.example.com/accounts/456")); assertThat(response.getHeaders().getFirst(CONTENT_LOCATION), is("https://api.example.com/accounts/456")); }
From source file:org.zalando.riptide.CaptureTest.java
@Test public void shouldCaptureResponse() throws IOException { server.expect(requestTo(url)).andRespond( withSuccess().body(new ClassPathResource("account.json")).contentType(APPLICATION_JSON)); final ClientHttpResponse response = unit.execute(GET, url) .dispatch(status(), on(OK).capture(), anyStatus().call(this::fail)).to(ClientHttpResponse.class); assertThat(response.getStatusCode(), is(OK)); assertThat(response.getHeaders().getContentType(), is(APPLICATION_JSON)); }
From source file:org.cloudfoundry.caldecott.client.HttpTunnel.java
private byte[] receiveDataBuffered(long page) { final String dataUrl = url + this.tunnelInfo.get("path_out") + "/" + page; byte[] responseBytes; try {//w w w . j a v a2 s . com responseBytes = restOperations.execute(dataUrl, HttpMethod.GET, new RequestCallback() { public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException { clientHttpRequest.getHeaders().set("Auth-Token", auth); } }, new ResponseExtractor<byte[]>() { public byte[] extractData(ClientHttpResponse clientHttpResponse) throws IOException { if (logger.isDebugEnabled()) { logger.debug("HEADER: " + clientHttpResponse.getHeaders().toString()); } InputStream stream = clientHttpResponse.getBody(); byte[] data = readContentData(stream); if (logger.isDebugEnabled()) { logger.debug("[" + data.length + " bytes] GET from " + dataUrl + " resulted in: " + clientHttpResponse.getStatusCode()); } return data; } }); } catch (HttpStatusCodeException e) { if (logger.isDebugEnabled()) { logger.debug("GET from " + dataUrl + " resulted in: " + e.getStatusCode().value()); } throw e; } return responseBytes; }
From source file:org.springframework.social.soundcloud.api.impl.SoundCloudErrorHandler.java
@SuppressWarnings("unchecked") private List<Map<String, String>> extractErrorDetailsFromResponse(ClientHttpResponse response) throws IOException { ObjectMapper mapper = new ObjectMapper(new JsonFactory()); List<String> authenticateHeaders = response.getHeaders().get("Www-Authenticate"); String authenticateHeader = authenticateHeaders == null || authenticateHeaders.size() == 0 ? null : authenticateHeaders.get(0); String json = null;//from w ww.j a v a2s.co m if (authenticateHeader != null) { json = "{" + authenticateHeader.replace('=', ':').replace("OAuth realm", "\"OAuth realm\"") .replace("error", "\"error\"") + "}"; try { Map<String, String> responseMap = mapper.<Map<String, String>>readValue(json, new TypeReference<Map<String, String>>() { }); List<Map<String, String>> errorsList = new ArrayList<Map<String, String>>(); if (responseMap.containsKey("error")) { Map<String, String> errorMap = new HashMap<String, String>(); errorMap.put("error_message", responseMap.get("error")); errorsList.add(errorMap); return errorsList; } } catch (JsonParseException e) { return null; } } else { json = readFully(response.getBody()); try { Map<String, Object> responseMap = mapper.<Map<String, Object>>readValue(json, new TypeReference<Map<String, Object>>() { }); if (responseMap.containsKey("errors")) { return (List<Map<String, String>>) responseMap.get("errors"); } else { return null; } } catch (JsonParseException e) { return null; } } return null; }
From source file:com.zhm.config.MyAuthorizationCodeAccessTokenProvider.java
protected ResponseExtractor<ResponseEntity<Void>> getAuthorizationResponseExtractor() { return new ResponseExtractor<ResponseEntity<Void>>() { public ResponseEntity<Void> extractData(ClientHttpResponse response) throws IOException { return new ResponseEntity<Void>(response.getHeaders(), response.getStatusCode()); }/*from w w w . j a v a 2 s .c o m*/ }; }
From source file:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.ApiResponseErrorHandler.java
/** * {@inheritDoc}// w w w . j a v a 2 s .co m * <p> * This implementation handles the HTTP error response by throwing an {@link ApiErrorResponseException} which includes * an {@link ApiError error} if the response body contained an API error entity. */ @Override public void handleError(ClientHttpResponse response) throws ApiErrorResponseException, IOException { HttpStatus statusCode = getHttpStatusCode(response); ApiError apiError = this.extractErrorResponse(response); throw new ApiErrorResponseException(statusCode.value(), response.getStatusText(), response.getHeaders(), getCharset(response), getResponseBody(response), apiError); }
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)); }//from ww w.ja v 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:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.ApiResponseErrorHandler.java
private HttpStatus getHttpStatusCode(ClientHttpResponse response) throws IOException { HttpStatus statusCode;//w w w. java 2 s .c om try { statusCode = response.getStatusCode(); } catch (IllegalArgumentException ex) { throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(), response.getHeaders(), getResponseBody(response), getCharset(response)); } return statusCode; }