List of usage examples for org.apache.http.client.methods CloseableHttpResponse getHeaders
Header[] getHeaders(String str);
From source file:fr.cnes.sitools.metacatalogue.resources.proxyservices.RedirectorHttps.java
/** * //w w w .j av a 2 s . c o m */ private void updateResponseWithOriginalCookies(Response response, CloseableHttpResponse closeableResponse) { Header[] cookieHeaders = closeableResponse.getHeaders("Set-Cookie"); Series<CookieSetting> cookieSettings = response.getCookieSettings(); for (int i = 0; i < cookieHeaders.length; i++) { String rawCookie = cookieHeaders[i].getValue(); String[] rawCookieParams = rawCookie.split(";"); // j = 0 String[] rawCookieNameAndValue = splitOnFirst(rawCookieParams[0], "="); String cookieName = rawCookieNameAndValue[0].trim(); String cookieValue = rawCookieNameAndValue[1].trim(); CookieSetting cS = new CookieSetting(1, cookieName, cookieValue); // j > 1 for (int j = 1; j < rawCookieParams.length; j++) { String param = rawCookieParams[j].trim(); if (param.indexOf("=") >= 0) { String[] params = splitOnFirst(param, "="); String paramName = params[0]; String paramValue = params[1]; if (paramName.equalsIgnoreCase("expires")) { // set expirydate ?? / max age ?? } else if (paramName.equalsIgnoreCase("domain")) { cS.setDomain(paramValue); } else if (paramName.equalsIgnoreCase("path")) { cS.setPath(paramValue); } else if (paramName.equalsIgnoreCase("comment")) { cS.setPath(paramValue); } } } cookieSettings.add(cS); } }
From source file:org.keycloak.testsuite.oauth.LoginStatusIframeEndpointTest.java
@Test public void checkIframeCache() throws IOException { String version = testingClient.server().fetch(new ServerVersion()); try (CloseableHttpClient client = HttpClients.createDefault()) { HttpGet get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html"); CloseableHttpResponse response = client.execute(get); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals("no-cache, must-revalidate, no-transform, no-store", response.getHeaders("Cache-Control")[0].getValue()); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html?version=" + version); response = client.execute(get);/*from w w w . j av a2 s. co m*/ assertEquals(200, response.getStatusLine().getStatusCode()); assertTrue(response.getHeaders("Cache-Control")[0].getValue().contains("max-age")); } }
From source file:plugins.KerberosSsoTest.java
private void assertUnauthenticatedRequestIsRejected(CloseableHttpClient httpClient) throws IOException { HttpGet get = new HttpGet(jenkins.url.toExternalForm()); CloseableHttpResponse response = httpClient.execute(get); assertEquals("Unauthorized", response.getStatusLine().getReasonPhrase()); assertEquals("Negotiate", response.getHeaders("WWW-Authenticate")[0].getValue()); }
From source file:org.ambraproject.wombat.service.remote.CachedRemoteService.java
/** * Requests a stream, using the "If-Modified-Since" header in the request so that the object will only be returned if * it was modified after the given time. Otherwise, the stream field of the returned object will be null. This is * useful when results from the SOA service are being added to a cache, and we only want to retrieve the result if it * is newer than the version stored in the cache. * * @param target the request to send the REST service * @param lastModified the object will be returned iff the SOA server indicates that it was modified after this * timestamp//from w ww. java2s. c o m * @return a timestamped stream, or a null stream with non-null timestamp * @throws IOException */ private TimestampedResponse requestIfModifiedSince(HttpUriRequest target, Calendar lastModified) throws IOException { Preconditions.checkNotNull(lastModified); CloseableHttpResponse response = null; boolean returningStream = false; try { target.addHeader(HttpHeaders.IF_MODIFIED_SINCE, HttpDateUtil.format(lastModified)); response = remoteService.getResponse(target); Header[] lastModifiedHeaders = response.getHeaders(HttpHeaders.LAST_MODIFIED); if (lastModifiedHeaders.length == 0) { TimestampedResponse timestamped = new TimestampedResponse(null, response); returningStream = true; return timestamped; } if (lastModifiedHeaders.length != 1) { throw new RuntimeException("Expecting 1 Last-Modified header, got " + lastModifiedHeaders.length); } Calendar resultLastModified = HttpDateUtil.parse(lastModifiedHeaders[0].getValue()); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.OK.value()) { TimestampedResponse timestamped = new TimestampedResponse(resultLastModified, response); returningStream = true; return timestamped; } else if (statusCode == HttpStatus.NOT_MODIFIED.value()) { return new TimestampedResponse(resultLastModified, null); } else { throw new RuntimeException("Unexpected status code " + statusCode); } } finally { if (!returningStream && response != null) { response.close(); } } }
From source file:org.fcrepo.camel.FcrepoClientTest.java
@Test public void testGet300() throws Exception { final int status = 300; final URI uri = create(baseUrl); final String redirect = baseUrl + "/bar"; final Header linkHeader = new BasicHeader("Link", "<" + redirect + ">; rel=\"describedby\""); final Header[] headers = new Header[] { linkHeader }; final CloseableHttpResponse mockResponse = doSetupMockRequest(RDF_XML, null, status); when(mockResponse.getHeaders("Link")).thenReturn(headers); final FcrepoResponse response = testClient.get(uri, RDF_XML, null); assertEquals(response.getUrl(), uri); assertEquals(response.getStatusCode(), status); assertEquals(response.getContentType(), RDF_XML); assertEquals(response.getLocation(), create(redirect)); assertEquals(response.getBody(), null); }
From source file:com.olacabs.fabric.compute.builder.impl.HttpJarDownloader.java
public Path download(final String url) { HttpGet httpGet = new HttpGet(URI.create(url)); CloseableHttpResponse response = null; try {/* www . j av a 2 s. c o m*/ response = httpClient.execute(httpGet); if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) { throw new RuntimeException(String.format("Server returned [%d][%s] for url: %s", response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), url)); } Header[] headers = response.getHeaders("Content-Disposition"); String filename = null; if (null != headers) { for (Header header : headers) { for (HeaderElement headerElement : header.getElements()) { if (!headerElement.getName().equalsIgnoreCase("attachment")) { continue; } NameValuePair attachment = headerElement.getParameterByName("filename"); if (attachment != null) { filename = attachment.getValue(); } } } } if (Strings.isNullOrEmpty(filename)) { String[] nameParts = url.split("/"); filename = nameParts[nameParts.length - 1]; } return Files.write(Paths.get(this.tmpDirectory, filename), EntityUtils.toByteArray(response.getEntity())); } catch (IOException e) { throw new RuntimeException("Error loading class from: " + url, e); } finally { if (null != response) { try { response.close(); } catch (IOException e) { LOGGER.error("Could not close connection to server: ", e); } } } }
From source file:org.piwigo.remotesync.api.client.WSClient.java
protected void checkMovedUrl(CloseableHttpResponse httpResponse) throws ClientRedirectException { if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) { String newLocation = "new location"; Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION); if (headers.length > 0) { newLocation = headers[0].getValue(); }//from www. ja v a2 s . c o m ClientRedirectException clientRedirectException = new ClientRedirectException( "Remote site moved to " + newLocation); clientRedirectException.setDestination(newLocation); throw clientRedirectException; } }
From source file:org.jboss.additional.testsuite.jdkall.present.web.servlet.buffersize.ResponseBufferSizeTestCase.java
@Test @OperateOnDeployment(DEPLOYMENT)/*from w w w . jav a 2s.c om*/ public void increaseBufferSizeTest(@ArquillianResource URL url) throws Exception { URL testURL = new URL( url.toString() + "ResponseBufferSizeServlet?" + ResponseBufferSizeServlet.SIZE_CHANGE_PARAM_NAME + "=1.5" + "&" + ResponseBufferSizeServlet.DATA_LENGTH_IN_PERCENTS_PARAM_NAME + "=0.8"); // more than original size, less than new buffer size final HttpGet request = new HttpGet(testURL.toString()); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; try { response = httpClient.execute(request); Assert.assertEquals("Failed to access " + testURL, HttpURLConnection.HTTP_OK, response.getStatusLine().getStatusCode()); String content = EntityUtils.toString(response.getEntity()); Assert.assertFalse(content.contains(ResponseBufferSizeServlet.RESPONSE_COMMITED_MESSAGE)); final Header[] transferEncodingHeaders = response.getHeaders("Transfer-Encoding"); final Header[] contentLengthHeader = response.getHeaders("Content-Length"); for (Header transferEncodingHeader : transferEncodingHeaders) { Assert.assertNotEquals( "Transfer-Encoding shouldn't be chunked as set BufferSize shouldn't be filled yet, " + "probably caused due https://bugzilla.redhat.com/show_bug.cgi?id=1212566", "chunked", transferEncodingHeader.getValue()); } Assert.assertFalse("Content-Length header not specified", contentLengthHeader.length == 0); } finally { IOUtils.closeQuietly(response); httpClient.close(); } }
From source file:org.dawnsci.marketplace.ui.editors.OverviewPage.java
private String getCsrfToken(CloseableHttpClient client) throws ClientProtocolException, IOException { String url = getMarketplaceUrl(); HttpHead head = new HttpHead(url + "token"); head.addHeader(X_CSRF_TOKEN, "fetch"); CloseableHttpResponse response = client.execute(head); EntityUtils.consume(response.getEntity()); String token = null;//from w ww.ja va 2 s. co m Header[] headers = response.getHeaders(X_CSRF_TOKEN); for (Header header : headers) { token = header.getValue(); } return token; }
From source file:net.yoomai.virgo.spider.Emulator.java
/** * /* ww w .j a va 2s . co m*/ * * @param params * @param url */ public String login(Map<String, String> params, String url) { String cookie = ""; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); List<NameValuePair> nvps = generateURLParams(params); try { httpPost.setEntity(new UrlEncodedFormEntity(nvps)); } catch (UnsupportedEncodingException e) { log.error(e.getMessage() + " : " + e.getCause()); } CloseableHttpResponse response = null; try { response = httpClient.execute(httpPost); } catch (IOException e) { log.error(e.getMessage() + " : " + e.getCause()); } if (response != null) { StatusLine statusLine = response.getStatusLine(); log.info(statusLine); if (statusLine.getStatusCode() == 200 || statusLine.getStatusCode() == 302) { Header[] headers = response.getHeaders("Set-Cookie"); for (Header header : headers) { cookie += header.getValue() + ";"; } } } return cookie; }