List of usage examples for org.apache.http.client.methods CloseableHttpResponse getAllHeaders
Header[] getAllHeaders();
From source file:org.openhim.mediator.engine.connectors.HTTPConnector.java
private MediatorHTTPResponse buildResponseFromOpenHIMJSONContent(MediatorHTTPRequest req, CloseableHttpResponse apacheResponse) throws IOException, CoreResponse.ParseException { String content = IOUtils.toString(apacheResponse.getEntity().getContent()); CoreResponse parsedContent = CoreResponse.parse(content); if (parsedContent.getResponse() == null) { throw new CoreResponse.ParseException( new Exception("No response object found in application/json+openhim content")); }//from w w w.j a v a2 s.c o m int status = apacheResponse.getStatusLine().getStatusCode(); if (parsedContent.getResponse().getStatus() != null) { status = parsedContent.getResponse().getStatus(); } Map<String, String> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (Header hdr : apacheResponse.getAllHeaders()) { headers.put(hdr.getName(), hdr.getValue()); } if (parsedContent.getResponse().getHeaders() != null) { for (String hdr : parsedContent.getResponse().getHeaders().keySet()) { headers.put(hdr, parsedContent.getResponse().getHeaders().get(hdr)); } } if (parsedContent.getOrchestrations() != null) { for (CoreResponse.Orchestration orch : parsedContent.getOrchestrations()) { req.getRequestHandler().tell(new AddOrchestrationToCoreResponse(orch), getSelf()); } } if (parsedContent.getProperties() != null) { for (String prop : parsedContent.getProperties().keySet()) { req.getRequestHandler().tell( new PutPropertyInCoreResponse(prop, parsedContent.getProperties().get(prop)), getSelf()); } } return new MediatorHTTPResponse(req, parsedContent.getResponse().getBody(), status, headers); }
From source file:org.wso2.carbon.bpmn.extensions.rest.RESTInvoker.java
/** * Invokes the http GET method/*w w w. ja v a 2 s . c o m*/ * * @param uri endpoint/service url * @param jsonHeaders header list * @param username username for authentication * @param password password for authentication * @return RESTResponse of the GET request (can be the response body or the response status code) * @throws Exception */ public RESTResponse invokeGET(URI uri, JsonNodeObject jsonHeaders, String username, String password) throws IOException { HttpGet httpGet = null; CloseableHttpResponse response = null; Header[] headers; int httpStatus; String contentType = null; String output = null; try { httpGet = new HttpGet(uri); processHeaderList(httpGet, jsonHeaders); response = sendReceiveRequest(httpGet, username, password); //response entity may be null (eg: 204 response) if (response.getEntity() != null) { output = IOUtils.toString(response.getEntity().getContent()); if (response.getEntity().getContentType() != null) { contentType = response.getEntity().getContentType().getValue(); } } headers = response.getAllHeaders(); httpStatus = response.getStatusLine().getStatusCode(); if (log.isTraceEnabled()) { log.trace("Invoked GET " + uri.toString() + " - Response message: " + output); } EntityUtils.consume(response.getEntity()); } finally { if (response != null) { IOUtils.closeQuietly(response); } if (httpGet != null) { httpGet.releaseConnection(); } } return new RESTResponse(contentType, output, headers, httpStatus); }
From source file:org.wso2.carbon.bpmn.extensions.rest.RESTInvoker.java
/** * Invokes the http PUT method/*ww w. j a va 2 s . c om*/ * * @param uri endpoint/service url * @param jsonHeaders header list * @param username username for authentication * @param password password for authentication * @param payload payload body passed * @return RESTResponse of the PUT request (can be the response body or the response status code) * @throws Exception */ public RESTResponse invokePUT(URI uri, JsonNodeObject jsonHeaders, String username, String password, String payload) throws IOException { HttpPut httpPut = null; CloseableHttpResponse response = null; Header[] headers; int httpStatus; String contentType = null; String output = null; try { httpPut = new HttpPut(uri); httpPut.setEntity(new StringEntity(payload, Charset.defaultCharset())); processHeaderList(httpPut, jsonHeaders); response = sendReceiveRequest(httpPut, username, password); if (response.getEntity() != null) { output = IOUtils.toString(response.getEntity().getContent()); if (response.getEntity().getContentType() != null) { contentType = response.getEntity().getContentType().getValue(); } } headers = response.getAllHeaders(); httpStatus = response.getStatusLine().getStatusCode(); if (log.isTraceEnabled()) { log.trace("Invoked PUT " + uri.toString() + " - Response message: " + output); } EntityUtils.consume(response.getEntity()); } finally { if (response != null) { IOUtils.closeQuietly(response); } if (httpPut != null) { httpPut.releaseConnection(); } } return new RESTResponse(contentType, output, headers, httpStatus); }
From source file:org.wso2.carbon.bpmn.extensions.rest.RESTInvoker.java
/** * Invokes the http POST method/*from ww w. j a va2s .co m*/ * * @param uri endpoint/service url * @param jsonHeaders header list * @param username username for authentication * @param password password for authentication * @param payload payload body passed * @return RESTResponse of the POST request (can be the response body or the response status code) * @throws Exception */ public RESTResponse invokePOST(URI uri, JsonNodeObject jsonHeaders, String username, String password, String payload) throws IOException { HttpPost httpPost = null; CloseableHttpResponse response = null; Header[] headers; int httpStatus; String contentType = null; String output = null; try { httpPost = new HttpPost(uri); httpPost.setEntity(new StringEntity(payload, Charset.defaultCharset())); processHeaderList(httpPost, jsonHeaders); response = sendReceiveRequest(httpPost, username, password); if (response.getEntity() != null) { output = IOUtils.toString(response.getEntity().getContent()); if (response.getEntity().getContentType() != null) { contentType = response.getEntity().getContentType().getValue(); } } headers = response.getAllHeaders(); httpStatus = response.getStatusLine().getStatusCode(); if (log.isTraceEnabled()) { log.trace("Invoked POST " + uri.toString() + " - Input payload: " + payload + " - Response message: " + output); } EntityUtils.consume(response.getEntity()); } finally { if (response != null) { IOUtils.closeQuietly(response); } if (httpPost != null) { httpPost.releaseConnection(); } } return new RESTResponse(contentType, output, headers, httpStatus); }
From source file:io.cloudslang.content.httpclient.CSHttpClient.java
public Map<String, String> parseResponse(CloseableHttpResponse httpResponse, String responseCharacterSet, String destinationFile, URI uri, HttpClientContext httpClientContext, CookieStore cookieStore, SerializableSessionObject cookieStoreSessionObject) { Map<String, String> result = new HashMap<>(); try {/*from www .j a v a2 s .co m*/ httpResponseConsumer.setHttpResponse(httpResponse).setResponseCharacterSet(responseCharacterSet) .setDestinationFile(destinationFile).consume(result); } catch (IOException e) { throw new RuntimeException(e); } finalLocationConsumer.setUri(uri).setRedirectLocations(httpClientContext.getRedirectLocations()) .setTargetHost(httpClientContext.getTargetHost()).consume(result); headersConsumer.setHeaders(httpResponse.getAllHeaders()).consume(result); statusConsumer.setStatusLine(httpResponse.getStatusLine()).consume(result); if (cookieStore != null) { try { cookieStoreSessionObject.setValue(CookieStoreBuilder.serialize(cookieStore)); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } result.put(RETURN_CODE, SUCCESS); return result; }
From source file:org.attribyte.api.http.impl.commons.Commons4Client.java
@Override public Response send(Request request, RequestOptions options) throws IOException { HttpUriRequest commonsRequest = null; switch (request.getMethod()) { case GET:/*from ww w. java 2 s .c o m*/ commonsRequest = new HttpGet(request.getURI()); break; case DELETE: commonsRequest = new HttpDelete(request.getURI()); break; case HEAD: commonsRequest = new HttpHead(request.getURI()); break; case POST: { HttpEntityEnclosingRequestBase entityEnclosingRequest = new HttpPost(request.getURI()); commonsRequest = entityEnclosingRequest; EntityBuilder entityBuilder = EntityBuilder.create(); if (request.getBody() != null) { entityBuilder.setBinary(request.getBody().toByteArray()); } else { Collection<Parameter> parameters = request.getParameters(); List<NameValuePair> nameValuePairs = Lists.newArrayListWithExpectedSize(parameters.size()); for (Parameter parameter : parameters) { String[] values = parameter.getValues(); for (String value : values) { nameValuePairs.add(new BasicNameValuePair(parameter.getName(), value)); } } } entityEnclosingRequest.setEntity(entityBuilder.build()); break; } case PUT: { HttpEntityEnclosingRequestBase entityEnclosingRequest = new HttpPut(request.getURI()); commonsRequest = entityEnclosingRequest; EntityBuilder entityBuilder = EntityBuilder.create(); if (request.getBody() != null) { entityBuilder.setBinary(request.getBody().toByteArray()); } entityEnclosingRequest.setEntity(entityBuilder.build()); break; } } Collection<Header> headers = request.getHeaders(); for (Header header : headers) { String[] values = header.getValues(); for (String value : values) { commonsRequest.setHeader(header.getName(), value); } } ResponseBuilder builder = new ResponseBuilder(); CloseableHttpResponse response = null; InputStream is = null; try { if (options.followRedirects != RequestOptions.DEFAULT_FOLLOW_REDIRECTS) { RequestConfig localConfig = RequestConfig.copy(defaultRequestConfig) .setRedirectsEnabled(options.followRedirects) .setMaxRedirects(options.followRedirects ? 5 : 0).build(); HttpClientContext localContext = HttpClientContext.create(); localContext.setRequestConfig(localConfig); response = httpClient.execute(commonsRequest, localContext); } else { response = httpClient.execute(commonsRequest); } builder.setStatusCode(response.getStatusLine().getStatusCode()); for (org.apache.http.Header header : response.getAllHeaders()) { builder.addHeader(header.getName(), header.getValue()); } HttpEntity entity = response.getEntity(); if (entity != null) { is = entity.getContent(); if (is != null) { builder.setBody(Request.bodyFromInputStream(is, options.maxResponseBytes)); } } } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { //TODO? } } if (response != null) { response.close(); } } return builder.create(); }
From source file:org.keycloak.testsuite.oauth.LoginStatusIframeEndpointTest.java
@Test public void checkIframe() throws IOException { CookieStore cookieStore = new BasicCookieStore(); try (CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build()) { String redirectUri = URLEncoder.encode( suiteContext.getAuthServerInfo().getContextRoot() + "/auth/admin/master/console", "UTF-8"); HttpGet get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/auth?response_type=code&client_id=" + Constants.ADMIN_CONSOLE_CLIENT_ID + "&redirect_uri=" + redirectUri); CloseableHttpResponse response = client.execute(get); String s = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); response.close();/*from w ww . j av a2 s .c om*/ String action = ActionURIUtils.getActionURIFromPageSource(s); HttpPost post = new HttpPost(action); List<NameValuePair> params = new LinkedList<>(); params.add(new BasicNameValuePair("username", "admin")); params.add(new BasicNameValuePair("password", "admin")); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(new UrlEncodedFormEntity(params)); response = client.execute(post); assertEquals("CP=\"This is not a P3P policy!\"", response.getFirstHeader("P3P").getValue()); Header setIdentityCookieHeader = null; Header setSessionCookieHeader = null; for (Header h : response.getAllHeaders()) { if (h.getName().equals("Set-Cookie")) { if (h.getValue().contains("KEYCLOAK_SESSION")) { setSessionCookieHeader = h; } else if (h.getValue().contains("KEYCLOAK_IDENTITY")) { setIdentityCookieHeader = h; } } } assertNotNull(setIdentityCookieHeader); assertTrue(setIdentityCookieHeader.getValue().contains("HttpOnly")); assertNotNull(setSessionCookieHeader); assertFalse(setSessionCookieHeader.getValue().contains("HttpOnly")); response.close(); Cookie sessionCookie = null; for (Cookie cookie : cookieStore.getCookies()) { if (cookie.getName().equals("KEYCLOAK_SESSION")) { sessionCookie = cookie; break; } } assertNotNull(sessionCookie); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html"); response = client.execute(get); assertEquals(200, response.getStatusLine().getStatusCode()); s = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); assertTrue(s.contains("function getCookie()")); assertEquals("CP=\"This is not a P3P policy!\"", response.getFirstHeader("P3P").getValue()); response.close(); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html/init"); response = client.execute(get); assertEquals(403, response.getStatusLine().getStatusCode()); response.close(); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html/init?" + "client_id=invalid" + "&origin=" + suiteContext.getAuthServerInfo().getContextRoot()); response = client.execute(get); assertEquals(403, response.getStatusLine().getStatusCode()); response.close(); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html/init?" + "client_id=" + Constants.ADMIN_CONSOLE_CLIENT_ID + "&origin=http://invalid"); response = client.execute(get); assertEquals(403, response.getStatusLine().getStatusCode()); response.close(); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html/init?" + "client_id=" + Constants.ADMIN_CONSOLE_CLIENT_ID + "&origin=" + suiteContext.getAuthServerInfo().getContextRoot()); response = client.execute(get); assertEquals(204, response.getStatusLine().getStatusCode()); response.close(); } }
From source file:it.tidalwave.bluemarine2.downloader.impl.DefaultDownloader.java
/******************************************************************************************************************* * * * ******************************************************************************************************************/ /* VisibleForTesting */ void onDownloadRequest(final @ListensTo @Nonnull DownloadRequest request) throws URISyntaxException { try {/*ww w . j a va 2 s . com*/ log.info("onDownloadRequest({})", request); URL url = request.getUrl(); for (;;) { final HttpCacheContext context = HttpCacheContext.create(); @Cleanup final CloseableHttpResponse response = httpClient.execute(new HttpGet(url.toURI()), context); final byte[] bytes = bytesFrom(response); final CacheResponseStatus cacheResponseStatus = context.getCacheResponseStatus(); log.debug(">>>> cacheResponseStatus: {}", cacheResponseStatus); final Origin origin = cacheResponseStatus.equals(CacheResponseStatus.CACHE_HIT) ? Origin.CACHE : Origin.NETWORK; // FIXME: shouldn't do this by myself // FIXME: upon configuration, everything should be cached (needed for supporting integration tests) if (!origin.equals(Origin.CACHE) && Arrays.asList(200, 303).contains(response.getStatusLine().getStatusCode())) { final Date date = new Date(); final Resource resource = new HeapResource(bytes); cacheStorage.putEntry(url.toExternalForm(), new HttpCacheEntry(date, date, response.getStatusLine(), response.getAllHeaders(), resource)); } // FIXME: if the redirect were enabled, we could drop this check if (request.isOptionPresent(DownloadRequest.Option.FOLLOW_REDIRECT) && response.getStatusLine().getStatusCode() == 303) // SEE_OTHER FIXME { url = new URL(response.getFirstHeader("Location").getValue()); log.info(">>>> following 'see also' to {} ...", url); } else { messageBus.publish(new DownloadComplete(request.getUrl(), response.getStatusLine().getStatusCode(), bytes, origin)); return; } } } catch (IOException e) { log.error("{}: {}", request.getUrl(), e.toString()); messageBus.publish(new DownloadComplete(request.getUrl(), -1, new byte[0], Origin.NETWORK)); } }
From source file:ch.cyberduck.core.sds.provider.HttpComponentsConnector.java
@Override public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException { final HttpUriRequest request = this.toUriHttpRequest(clientRequest); final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request); try {//ww w.ja va 2s. co m final CloseableHttpResponse response; response = client.execute(new HttpHost(request.getURI().getHost(), request.getURI().getPort(), request.getURI().getScheme()), request, new BasicHttpContext(context)); HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(), this.getClass().getName()); final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null ? Statuses.from(response.getStatusLine().getStatusCode()) : Statuses.from(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); final ClientResponse responseContext = new ClientResponse(status, clientRequest); final List<URI> redirectLocations = context.getRedirectLocations(); if (redirectLocations != null && !redirectLocations.isEmpty()) { responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1)); } final Header[] respHeaders = response.getAllHeaders(); final MultivaluedMap<String, String> headers = responseContext.getHeaders(); for (final Header header : respHeaders) { final String headerName = header.getName(); List<String> list = headers.get(headerName); if (list == null) { list = new ArrayList<>(); } list.add(header.getValue()); headers.put(headerName, list); } final HttpEntity entity = response.getEntity(); if (entity != null) { if (headers.get(HttpHeaders.CONTENT_LENGTH) == null) { headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength())); } final Header contentEncoding = entity.getContentEncoding(); if (headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) { headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue()); } } responseContext.setEntityStream(this.toInputStream(response)); return responseContext; } catch (final Exception e) { throw new ProcessingException(e); } }
From source file:org.commonjava.aprox.client.core.AproxClientHttp.java
public Map<String, String> head(final String path, final int... responseCodes) throws AproxClientException { connect();//from www.j a va 2 s. c om HttpHead request = null; CloseableHttpResponse response = null; CloseableHttpClient client = null; try { request = newJsonHead(buildUrl(baseUrl, path)); client = newClient(); response = client.execute(request); final StatusLine sl = response.getStatusLine(); if (!validResponseCode(sl.getStatusCode(), responseCodes)) { if (sl.getStatusCode() == HttpStatus.SC_NOT_FOUND) { return null; } throw new AproxClientException("Error executing HEAD: %s. Status was: %d %s (%s)", path, sl.getStatusCode(), sl.getReasonPhrase(), sl.getProtocolVersion()); } final Map<String, String> headers = new HashMap<>(); for (final Header header : response.getAllHeaders()) { final String name = header.getName().toLowerCase(); if (!headers.containsKey(name)) { headers.put(name, header.getValue()); } } return headers; } catch (final IOException e) { throw new AproxClientException("AProx request failed: %s", e, e.getMessage()); } finally { cleanupResources(request, response, client); } }