List of usage examples for org.apache.http.client.methods CloseableHttpResponse getHeaders
Header[] getHeaders(String str);
From source file:uk.org.openeyes.oink.itest.adapters.ITFacadeToProxy.java
@Test public void testCreateAndDeletePractitioners() throws Exception { String facadeUri = (String) facadeProps.get("facade.uri"); URIBuilder builder = new URIBuilder(facadeUri); URI uri = builder.setPath(builder.getPath() + "/Practitioner") .setParameter("_profile", "http://openeyes.org.uk/fhir/1.7.0/profile/Practitioner/Gp").build(); System.out.println(uri.toString()); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(uri); httpPost.addHeader("Accept", "application/json+fhir; charset=UTF-8"); httpPost.addHeader("Category", "http://openeyes.org.uk/fhir/1.7.0/profile/Practitioner/Gp; scheme=\"http://hl7.org/fhir/tag/profile\"; label=\"\""); httpPost.addHeader("Content-Type", "application/json+fhir"); InputStream is = getClass().getResourceAsStream("/example-messages/fhir/practitioner.json"); StringWriter writer = new StringWriter(); IOUtils.copy(is, writer);//from w w w . j a va2 s . c o m String theString = writer.toString(); StringEntity isEntity = new StringEntity(theString); httpPost.setEntity(isEntity); CloseableHttpResponse response1 = httpclient.execute(httpPost); assertEquals(201, response1.getStatusLine().getStatusCode()); // Note location header is the real end-server location not the facade // e.g. http://192.168.1.100/api/Practitioner/gp-4/_history/1401366763 String locationHeader = response1.getHeaders("Location")[0].getValue(); assertNotNull(locationHeader); String resourceId = extractResourceIdFromUri(locationHeader); assertNotNull(resourceId); URIBuilder builder2 = new URIBuilder(facadeUri); URI uri2 = builder2.setPath(builder2.getPath() + "/Practitioner/" + resourceId) .setParameter("_profile", "http://openeyes.org.uk/fhir/1.7.0/profile/Practitioner/Gp").build(); HttpDelete httpDelete = new HttpDelete(uri2); CloseableHttpResponse response2 = httpclient.execute(httpDelete); assertEquals(204, response2.getStatusLine().getStatusCode()); }
From source file:de.goldbachinteractive.gbi.redirecthandler.client.Error404HandlerServlet.java
/** * Requests a redirect processor for redirect (with the original request as * parameter r).//from w w w. j av a 2 s . c o m * * @param redirectProcessorUrl * The redirect processor to use (with the original request as * parameter r). * @param httpClient * The HttpClient to execute the request. * @param req * The original request. * @param resp * The original response. * @param timeout * The timeout for request. * @return True, if redirected or false, if not. */ private boolean redirectRequest(String redirectProcessorUrl, CloseableHttpClient httpClient, HttpServletRequest req, HttpServletResponse resp, int timeout) { try { HttpGet httpGet = new HttpGet(redirectProcessorUrl); httpGet.setConfig(RequestConfig.custom().setRedirectsEnabled(false).setSocketTimeout(timeout).build()); // copy all headers from original request final Enumeration<String> headers = req.getHeaderNames(); while (headers.hasMoreElements()) { final String header = headers.nextElement(); if (header.equalsIgnoreCase("host")) { continue; } final Enumeration<String> values = req.getHeaders(header); while (values.hasMoreElements()) { final String value = values.nextElement(); httpGet.setHeader(header, value); } } // to remove host header if (httpGet.getHeaders("host") != null) { httpGet.removeHeaders("host"); } // to add X-gbi-key header httpGet.setHeader(GBI_KEY_HEADER, xGbiKey); CloseableHttpResponse response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); logger.info(String.format("status code :%d", statusCode)); if (statusCode >= 300 && statusCode < 400) { // if status code is 3XX, the Location header of response is set String location = response.getHeaders("Location")[0].getValue(); resp.sendRedirect(location); return true; } } catch (Exception e) { logger.error(String.format("error while trying to request redirect:[%s]", e.getMessage()), e); } return false; }
From source file:com.granita.icloudcalsync.webdav.WebDavResource.java
public void options() throws URISyntaxException, IOException, HttpException { HttpOptionsHC4 options = new HttpOptionsHC4(location); @Cleanup CloseableHttpResponse response = httpClient.execute(options, context); checkResponse(response);// w w w.j av a 2 s . c o m Header[] allowHeaders = response.getHeaders("Allow"); for (Header allowHeader : allowHeaders) methods.addAll(Arrays.asList(allowHeader.getValue().split(", ?"))); Header[] capHeaders = response.getHeaders("DAV"); for (Header capHeader : capHeaders) capabilities.addAll(Arrays.asList(capHeader.getValue().split(", ?"))); }
From source file:io.crate.integrationtests.BlobHttpIntegrationTest.java
public List<String> getRedirectLocations(CloseableHttpClient client, String uri, InetSocketAddress address) throws IOException { CloseableHttpResponse response = null; try {// w w w . j av a 2 s .c om HttpClientContext context = HttpClientContext.create(); HttpHead httpHead = new HttpHead(String.format(Locale.ENGLISH, "http://%s:%s/_blobs/%s", address.getHostName(), address.getPort(), uri)); response = client.execute(httpHead, context); List<URI> redirectLocations = context.getRedirectLocations(); if (redirectLocations == null) { // client might not follow redirects automatically if (response.containsHeader("location")) { List<String> redirects = new ArrayList<>(1); for (Header location : response.getHeaders("location")) { redirects.add(location.getValue()); } return redirects; } return Collections.emptyList(); } List<String> redirects = new ArrayList<>(1); for (URI redirectLocation : redirectLocations) { redirects.add(redirectLocation.toString()); } return redirects; } finally { if (response != null) { IOUtils.closeWhileHandlingException(response); } } }
From source file:com.activiti.service.activiti.ActivitiClientService.java
public JsonNode executeDownloadRequest(HttpUriRequest request, HttpServletResponse httpResponse, String userName, String password, int expectedStatusCode) { ActivitiServiceException exception = null; CloseableHttpClient client = getHttpClient(userName, password); try {/*from w w w. ja v a 2 s . c o m*/ CloseableHttpResponse response = client.execute(request); try { boolean success = response.getStatusLine() != null && response.getStatusLine().getStatusCode() == expectedStatusCode; if (success) { httpResponse.setHeader("Content-Disposition", response.getHeaders("Content-Disposition")[0].getValue()); response.getEntity().writeTo(httpResponse.getOutputStream()); return null; } else { JsonNode bodyNode = null; String strResponse = IOUtils.toString(response.getEntity().getContent()); try { bodyNode = objectMapper.readTree(strResponse); } catch (Exception e) { log.debug("Error parsing error message", e); } exception = new ActivitiServiceException(extractError(bodyNode, "An error occured while calling Activiti: " + response.getStatusLine())); } } catch (Exception e) { log.warn("Error consuming response from uri " + request.getURI(), e); exception = wrapException(e, request); } finally { response.close(); } } catch (Exception e) { log.error("Error executing request to uri " + request.getURI(), e); exception = wrapException(e, request); } finally { try { client.close(); } catch (Exception e) { log.warn("Error closing http client instance", e); } } if (exception != null) { throw exception; } return null; }
From source file:org.riotfamily.crawler.HttpClientPageLoader.java
public PageData loadPage(Href href) { String url = href.getResolvedUri(); PageData pageData = new PageData(href); log.info("Loading page: " + url); HttpGet get = null;//from ww w . j a v a 2 s .c o m try { get = new HttpGet(url); if (StringUtils.hasText(href.getReferrerUrl())) { get.addHeader(ServletUtils.REFERER_HEADER, href.getReferrerUrl()); } prepareMethod(get); CloseableHttpResponse httpResponse = client.execute(get); int statusCode = httpResponse.getStatusLine().getStatusCode(); pageData.setStatusCode(statusCode); if (statusCode == HttpStatus.SC_OK) { try { HttpEntity entity = httpResponse.getEntity(); if (accept(entity)) { String content = EntityUtils.toString(entity, Consts.UTF_8); pageData.setHtml(content); Header[] headers = httpResponse.getAllHeaders(); for (int i = 0; i < headers.length; i++) { pageData.addHeader(headers[i].getName(), headers[i].getValue()); } } } finally { httpResponse.close(); } } else { log.info("Status: " + statusCode); Header[] locationHeaders = httpResponse.getHeaders("Location"); if (locationHeaders != null && locationHeaders.length == 1) { pageData.setRedirectUrl(locationHeaders[0].getValue()); } else { pageData.setError(httpResponse.getStatusLine().toString()); } } } catch (Exception e) { pageData.setError(e.getMessage()); log.warn(e.getMessage()); } finally { try { if (get != null) { get.releaseConnection(); } } catch (Exception e) { } } return pageData; }
From source file:org.esigate.DriverTest.java
/** * This test ensure Fetch events are fired when cache is disabled. * <p>// www . j a v a 2s . c om * It uses {@link DefaultCharset} extension which processes the Contet-Type header on post-fetch events. * * @throws Exception */ public void testBug185() throws Exception { Properties properties = new Properties(); properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://www.foo.com/"); properties.put(Parameters.EXTENSIONS.getName(), DefaultCharset.class.getName()); properties.put(Parameters.USE_CACHE.getName(), "false"); HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "Not Modified"); response.addHeader("Content-Type", "text/html"); mockConnectionManager.setResponse(response); Driver driver = createMockDriver(properties, mockConnectionManager); // Request request = TestUtils.createIncomingRequest("http://www.bar142-2.com/foobar142-2/"); CloseableHttpResponse driverResponse = driver.proxy("/foobar142-2/", request.build()); assertEquals(HttpStatus.SC_OK, driverResponse.getStatusLine().getStatusCode()); assertEquals("text/html; charset=ISO-8859-1", driverResponse.getHeaders("Content-Type")[0].getValue()); // Same test with cache enabled properties.put(Parameters.USE_CACHE.getName(), "true"); response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "Not Modified"); response.addHeader("Content-Type", "text/html"); mockConnectionManager.setResponse(response); driver = createMockDriver(properties, mockConnectionManager); // Request request = TestUtils.createIncomingRequest("http://www.bar142-2.com/foobar142-2/"); driverResponse = driver.proxy("/foobar142-2/", request.build()); assertEquals(HttpStatus.SC_OK, driverResponse.getStatusLine().getStatusCode()); assertEquals("text/html; charset=ISO-8859-1", driverResponse.getHeaders("Content-Type")[0].getValue()); }
From source file:com.activiti.service.activiti.ActivitiClientService.java
public AttachmentResponseInfo executeDownloadRequest(HttpUriRequest request, String userName, String password, Integer... expectedStatusCodes) { ActivitiServiceException exception = null; CloseableHttpClient client = getHttpClient(userName, password); try {// w w w . j ava 2 s .c o m CloseableHttpResponse response = client.execute(request); try { int statusCode = -1; if (response.getStatusLine() != null) { statusCode = response.getStatusLine().getStatusCode(); } boolean success = Arrays.asList(expectedStatusCodes).contains(statusCode); if (success) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String contentDispositionFileName[] = response.getHeaders("Content-Disposition")[0] .getValue().split("="); String fileName = contentDispositionFileName[contentDispositionFileName.length - 1]; return new AttachmentResponseInfo(fileName, IOUtils.toByteArray(response.getEntity().getContent())); } else { return new AttachmentResponseInfo(statusCode, readJsonContent(response.getEntity().getContent())); } } else { exception = new ActivitiServiceException( extractError(readJsonContent(response.getEntity().getContent()), "An error occured while calling Activiti: " + response.getStatusLine())); } } catch (Exception e) { log.warn("Error consuming response from uri " + request.getURI(), e); exception = wrapException(e, request); } finally { response.close(); } } catch (Exception e) { log.error("Error executing request to uri " + request.getURI(), e); exception = wrapException(e, request); } finally { try { client.close(); } catch (Exception e) { log.warn("Error closing http client instance", e); } } if (exception != null) { throw exception; } return null; }
From source file:io.uploader.drive.drive.largefile.DriveResumableUpload.java
public long getCurrentByte() throws IOException { logger.info("Querying status of resumable upload..."); CloseableHttpClient httpclient = null; CloseableHttpResponse response = null; long lastbyte = -1; try {//from w ww . j a v a2 s . com httpclient = getHttpClient(); BasicHttpRequest httpreq = new BasicHttpRequest("PUT", location); httpreq.addHeader("Authorization", auth.getAuthHeader()); httpreq.addHeader("Content-Length", "0"); httpreq.addHeader("Content-Range", "bytes */" + getFileSizeString()); //logger.info(httpreq.toString()); response = httpclient.execute(URIUtils.extractHost(uri), httpreq); @SuppressWarnings("unused") BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity()); EntityUtils.consume(response.getEntity()); if (response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201) { lastbyte = fileSize; } if (response.getStatusLine().getStatusCode() == 308) { if (response.getHeaders("Range").length > 0) { String range = response.getHeaders("Range")[0].getValue(); String[] parts = range.split("-"); lastbyte = Long.parseLong(parts[1]) + 1; } else { // nothing uploaded, but file is there to start upload! lastbyte = 0; } } return lastbyte; } finally { if (response != null) { response.close(); } if (httpclient != null) { httpclient.close(); } } }
From source file:eu.peppol.outbound.HttpPostTestIT.java
@Test public void testPost() throws Exception { InputStream resourceAsStream = HttpPostTestIT.class.getClassLoader() .getResourceAsStream(PEPPOL_BIS_INVOICE_SBDH_XML); assertNotNull(resourceAsStream,// w w w. ja v a2s . co m "Unable to locate resource " + PEPPOL_BIS_INVOICE_SBDH_XML + " in class path"); X509Certificate ourCertificate = keystoreManager.getOurCertificate(); SMimeMessageFactory SMimeMessageFactory = new SMimeMessageFactory(keystoreManager.getOurPrivateKey(), ourCertificate); MimeMessage signedMimeMessage = SMimeMessageFactory.createSignedMimeMessage(resourceAsStream, new MimeType("application/xml")); signedMimeMessage.writeTo(System.out); CloseableHttpClient httpClient = createCloseableHttpClient(); HttpPost httpPost = new HttpPost(OXALIS_AS2_URL); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); signedMimeMessage.writeTo(byteArrayOutputStream); X500Principal subjectX500Principal = ourCertificate.getSubjectX500Principal(); CommonName commonNameOfSender = CommonName.valueOf(subjectX500Principal); PeppolAs2SystemIdentifier asFrom = PeppolAs2SystemIdentifier.valueOf(commonNameOfSender); httpPost.addHeader(As2Header.AS2_FROM.getHttpHeaderName(), asFrom.toString()); httpPost.addHeader(As2Header.AS2_TO.getHttpHeaderName(), new PeppolAs2SystemIdentifier(PeppolAs2SystemIdentifier.AS2_SYSTEM_ID_PREFIX + "AS2-TEST") .toString()); httpPost.addHeader(As2Header.DISPOSITION_NOTIFICATION_OPTIONS.getHttpHeaderName(), As2DispositionNotificationOptions.getDefault().toString()); httpPost.addHeader(As2Header.AS2_VERSION.getHttpHeaderName(), As2Header.VERSION); httpPost.addHeader(As2Header.SUBJECT.getHttpHeaderName(), "AS2 TEST MESSAGE"); httpPost.addHeader(As2Header.MESSAGE_ID.getHttpHeaderName(), UUID.randomUUID().toString()); httpPost.addHeader(As2Header.DATE.getHttpHeaderName(), As2DateUtil.format(new Date())); // Inserts the S/MIME message to be posted httpPost.setEntity( new ByteArrayEntity(byteArrayOutputStream.toByteArray(), ContentType.create("multipart/signed"))); CloseableHttpResponse postResponse = null; // EXECUTE !!!! try { postResponse = httpClient.execute(httpPost); } catch (HttpHostConnectException e) { fail("The Oxalis server does not seem to be running at " + OXALIS_AS2_URL); } HttpEntity entity = postResponse.getEntity(); // Any results? Assert.assertEquals(postResponse.getStatusLine().getStatusCode(), 200); String contents = EntityUtils.toString(entity); assertNotNull(contents); if (log.isDebugEnabled()) { log.debug("Received: \n"); Header[] allHeaders = postResponse.getAllHeaders(); for (Header header : allHeaders) { log.debug("" + header.getName() + ": " + header.getValue()); } log.debug("\n" + contents); log.debug("---------------------------"); } try { MimeMessage mimeMessage = MimeMessageHelper.parseMultipart(contents); System.out.println("Received multipart MDN response decoded as type : " + mimeMessage.getContentType()); // Make sure we set content type header for the multipart message (should be multipart/signed) String contentTypeFromHttpResponse = postResponse.getHeaders("Content-Type")[0].getValue(); // Oxalis always return only one mimeMessage.setHeader("Content-Type", contentTypeFromHttpResponse); Enumeration<String> headerlines = mimeMessage.getAllHeaderLines(); while (headerlines.hasMoreElements()) { // Content-Type: multipart/signed; // protocol="application/pkcs7-signature"; // micalg=sha-1; // boundary="----=_Part_3_520186210.1399207766925" System.out.println("HeaderLine : " + headerlines.nextElement()); } MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage); String msg = mdnMimeMessageInspector.getPlainTextPartAsText(); System.out.println(msg); } finally { postResponse.close(); } }