List of usage examples for org.apache.http.client.methods CloseableHttpResponse getAllHeaders
Header[] getAllHeaders();
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 ww .j a v a2s. c om*/ "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(); } }
From source file:ServerJniTest.java
@Test public void testHeaders() throws Exception { long handle = 0; try {/*from w w w . j a v a2 s . c o m*/ String sout = wiltoncall("server_create", GSON.toJson( ImmutableMap.builder().put("views", TestGateway.views()).put("tcpPort", TCP_PORT).build())); Map<String, Long> shamap = GSON.fromJson(sout, LONG_MAP_TYPE); handle = shamap.get("serverHandle"); assertEquals(HELLO_RESP, httpGet(ROOT_URL + "hello")); CloseableHttpResponse resp = null; String output; Map<String, String> serverHeaders = new LinkedHashMap<String, String>(); try { HttpGet get = new HttpGet(ROOT_URL + "headers"); get.addHeader("X-Dupl-H", "foo"); get.addHeader("X-Dupl-H", "bar"); get.addHeader("Referer", "foo"); get.addHeader("referer", "bar"); resp = http.execute(get); for (Header he : resp.getAllHeaders()) { serverHeaders.put(he.getName(), he.getValue()); } output = EntityUtils.toString(resp.getEntity(), "UTF-8"); } finally { closeQuietly(resp); } Map<String, String> clientHeaders = GSON.fromJson(output, STRING_MAP_TYPE); assertTrue(clientHeaders.containsKey("X-Dupl-H")); assertTrue(clientHeaders.get("X-Dupl-H").contains("foo")); assertTrue(clientHeaders.get("X-Dupl-H").contains("bar")); assertTrue(clientHeaders.get("X-Dupl-H").contains(",")); assertTrue(clientHeaders.containsKey("referer") || clientHeaders.containsKey("Referer")); if (clientHeaders.containsKey("referer")) { assertEquals("bar", clientHeaders.get("referer")); } else { assertEquals("foo", clientHeaders.get("Referer")); } assertEquals("foo", serverHeaders.get("X-Server-H1")); assertEquals("bar", serverHeaders.get("X-Server-H2")); assertTrue(serverHeaders.get("X-Proto").equals("http")); } finally { stopServerQuietly(handle); } }
From source file:org.lokra.seaweedfs.core.Connection.java
/** * Fetch http API hearers with status code(in array). * * @param request Only http method head. * @return Header fetch by http response. * @throws IOException Http connection is fail or server response within some error message. *//*from w w w . j a v a2 s . com*/ HeaderResponse fetchHeaderByRequest(HttpHead request) throws IOException { CloseableHttpResponse response = null; request.setHeader("Connection", "close"); HeaderResponse headerResponse; try { response = httpClient.execute(request, HttpClientContext.create()); headerResponse = new HeaderResponse(response.getAllHeaders(), response.getStatusLine().getStatusCode()); } finally { if (response != null) { try { response.close(); } catch (IOException ignored) { } } request.releaseConnection(); } return headerResponse; }
From source file:com.mirth.connect.client.core.ServerConnection.java
private ClientResponse handleResponse(ClientRequest request, HttpRequestBase requestBase, CloseableHttpResponse response, boolean sync) throws IOException, ClientException { StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); ClientResponse responseContext = new MirthClientResponse(Statuses.from(statusCode), request); MultivaluedMap<String, String> headerMap = new MultivaluedHashMap<String, String>(); for (Header header : response.getAllHeaders()) { headerMap.add(header.getName(), header.getValue()); }//w w w. ja v a 2 s . c o m responseContext.headers(headerMap); HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { responseContext .setEntityStream(new EntityInputStreamWrapper(response, responseEntity.getContent(), sync)); } if (statusCode == HttpStatus.SC_UNAUTHORIZED) { if (responseContext.hasEntity()) { try { Object entity = responseContext.readEntity(Object.class); throw new UnauthorizedException(statusLine.toString(), entity); } catch (ProcessingException e) { } } throw new UnauthorizedException(statusLine.toString()); } else if (statusCode == HttpStatus.SC_FORBIDDEN) { throw new ForbiddenException(statusLine.toString()); } if (statusCode >= 400) { if (responseContext.hasEntity()) { try { Object entity = responseContext.readEntity(Object.class); if (entity instanceof Throwable) { throw new ClientException("Method failed: " + statusLine, (Throwable) entity); } } catch (ProcessingException e) { } } throw new ClientException("Method failed: " + statusLine); } return responseContext; }
From source file:eu.peppol.outbound.transmission.As2MessageSender.java
/** * Handles the HTTP 200 POST response (the MDN with status indications) * * @param transmissionId the transmissionId (used in HTTP headers as Message-ID) * @param outboundMic the calculated mic of the payload (should be verified against the one returned in MDN) * @param postResponse the http response to be decoded as MDN * @return//ww w. j a va 2 s .com */ MimeMessage handleTheHttpResponse(TransmissionId transmissionId, Mic outboundMic, CloseableHttpResponse postResponse, SmpLookupManager.PeppolEndpointData peppolEndpointData) { try { HttpEntity entity = postResponse.getEntity(); // Any textual results? if (entity == null) { throw new IllegalStateException( "No contents in HTTP response with rc=" + postResponse.getStatusLine().getStatusCode()); } String contents = EntityUtils.toString(entity); if (traceEnabled) { log.debug("HTTP-headers:"); Header[] allHeaders = postResponse.getAllHeaders(); for (Header header : allHeaders) { log.debug("" + header.getName() + ": " + header.getValue()); } log.debug("Contents:\n" + contents); log.debug("---------------------------"); } Header contentTypeHeader = postResponse.getFirstHeader("Content-Type"); if (contentTypeHeader == null) { throw new IllegalStateException("No Content-Type header in response, probably a server error"); } String contentType = contentTypeHeader.getValue(); MimeMessage mimeMessage = null; try { mimeMessage = MimeMessageHelper.parseMultipart(contents, new MimeType(contentType)); try { mimeMessage.writeTo(System.out); } catch (MessagingException e) { throw new IllegalStateException("Unable to print mime message"); } } catch (MimeTypeParseException e) { throw new IllegalStateException("Invalid Content-Type header"); } // verify the signature of the MDN, we warn about dodgy signatures try { SignedMimeMessage signedMimeMessage = new SignedMimeMessage(mimeMessage); X509Certificate cert = signedMimeMessage.getSignersX509Certificate(); cert.checkValidity(); // Verify if the certificate used by the receiving Access Point in // the response message does not match its certificate published by the SMP if (peppolEndpointData.getCommonName() == null || !CommonName .valueOf(cert.getSubjectX500Principal()).equals(peppolEndpointData.getCommonName())) { throw new CertificateException( "Common name in certificate from SMP does not match common name in AP certificate"); } log.debug("MDN signature was verfied for : " + cert.getSubjectDN().toString()); } catch (Exception ex) { log.warn("Exception when verifying MDN signature : " + ex.getMessage()); } // Verifies the actual MDN MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage); String msg = mdnMimeMessageInspector.getPlainTextPartAsText(); if (mdnMimeMessageInspector.isOkOrWarning(outboundMic)) { return mimeMessage; } else { log.error("AS2 transmission failed with some error message, msg :" + msg); log.error(contents); throw new IllegalStateException("AS2 transmission failed : " + msg); } } catch (IOException e) { throw new IllegalStateException("Unable to obtain the contents of the response: " + e.getMessage(), e); } finally { try { postResponse.close(); } catch (IOException e) { throw new IllegalStateException("Unable to close http connection: " + e.getMessage(), e); } } }
From source file:edu.harvard.hul.ois.drs.pdfaconvert.clients.HttpClientIntegrationTest.java
@Test public void doGetTest() throws URISyntaxException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL fileUrl = loader.getResource(INPUT_FILENAME); File inputFile = new File(fileUrl.toURI()); assertNotNull(inputFile);//from ww w . j a v a 2 s.c om assertTrue(inputFile.exists()); assertTrue(inputFile.isFile()); assertTrue(inputFile.canRead()); CloseableHttpClient httpclient = HttpClients.createDefault(); String fileLocation = fileUrl.getPath(); String url = LOCAL_TOMCAT_SERVICE_URL + "?file=" + fileLocation; HttpGet httpGet = new HttpGet(url); CloseableHttpResponse response = null; try { logger.debug("executing request " + httpGet.getRequestLine()); response = httpclient.execute(httpGet); StatusLine statusLine = response.getStatusLine(); logger.debug("Response status line : " + statusLine); HttpEntity entity = response.getEntity(); if (entity != null) { long len = entity.getContentLength(); if (len != -1 && len < 2048) { logger.debug("len: " + len); logger.debug(EntityUtils.toString(entity)); } else { logger.debug("len: " + len); Header[] allHeaders = response.getAllHeaders(); for (Header h : allHeaders) { logger.debug("Header: name:" + h.getName() + " -- value: " + h.getValue() + " -- toString(): " + h); } Header header = entity.getContentEncoding(); header = entity.getContentType(); logger.debug("header content type: " + header.toString()); header = response.getFirstHeader("filename"); String filename = header.getValue(); String savedFilename = filename == null ? "file.pdf" : filename; InputStream is = entity.getContent(); OutputStream out = new FileOutputStream("target/" + savedFilename); int bytesCnt; while ((bytesCnt = is.read()) != -1) { out.write(bytesCnt); } out.close(); } } } catch (IOException e) { logger.error("Something went wrong...", e); fail(e.getMessage()); } finally { if (response != null) { try { response.close(); httpclient.close(); } catch (IOException e) { // nothing to do ; } } } logger.debug("DONE"); }
From source file:edu.harvard.hul.ois.drs.pdfaconvert.clients.HttpClientIntegrationTest.java
@Test public void doPostTest() throws URISyntaxException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL fileUrl = loader.getResource(INPUT_FILENAME); File inputFile = new File(fileUrl.toURI()); assertNotNull(inputFile);/*from ww w . j av a 2s .c o m*/ assertTrue(inputFile.exists()); assertTrue(inputFile.isFile()); assertTrue(inputFile.canRead()); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(LOCAL_TOMCAT_SERVICE_URL); FileBody fileContent = new FileBody(inputFile); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart(FORM_FIELD_DATAFILE, fileContent).build(); httpPost.setEntity(reqEntity); CloseableHttpResponse response = null; try { logger.debug("executing request " + httpPost.getRequestLine()); response = httpclient.execute(httpPost); StatusLine statusLine = response.getStatusLine(); logger.debug("Response status line : " + statusLine); HttpEntity entity = response.getEntity(); if (entity != null) { long len = entity.getContentLength(); if (len != -1 && len < 2048) { logger.debug("len: " + len); logger.debug(EntityUtils.toString(entity)); } else { logger.debug("len: " + len); Header[] allHeaders = response.getAllHeaders(); for (Header h : allHeaders) { logger.debug("Header: name:" + h.getName() + " -- value: " + h.getValue() + " -- toString(): " + h); } Header header = entity.getContentEncoding(); // logger.debug("header encoding: " + header.toString()); header = entity.getContentType(); logger.debug("header content type: " + header.toString()); header = response.getFirstHeader("filename"); String filename = header.getValue(); String savedFilename = filename == null ? "file.pdf" : filename; InputStream is = entity.getContent(); OutputStream out = new FileOutputStream("target/" + savedFilename); int bytesCnt; while ((bytesCnt = is.read()) != -1) { out.write(bytesCnt); } out.close(); } } } catch (IOException e) { logger.error("Something went wrong...", e); fail(e.getMessage()); } finally { if (response != null) { try { response.close(); httpclient.close(); } catch (IOException e) { // nothing to do ; } } } logger.debug("DONE"); }
From source file:org.wso2.carbon.bpmn.extensions.rest.RESTInvoker.java
/** * Invokes the http DELETE method/*from w ww. ja va 2 s . c om*/ * * @param uri endpoint/service url * @param jsonHeaders header list * @param username username for authentication * @param password password for authentication * @return RESTResponse of the DELETE (can be the response status code or the response body) * @throws Exception */ public RESTResponse invokeDELETE(URI uri, JsonNodeObject jsonHeaders, String username, String password) throws IOException { HttpDelete httpDelete = null; CloseableHttpResponse response = null; Header[] headers; int httpStatus; String contentType = null; String output = null; try { httpDelete = new HttpDelete(uri); processHeaderList(httpDelete, jsonHeaders); response = sendReceiveRequest(httpDelete, 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 DELETE " + uri.toString() + " - Response message: " + output); } EntityUtils.consume(response.getEntity()); } finally { if (response != null) { IOUtils.closeQuietly(response); } if (httpDelete != null) { httpDelete.releaseConnection(); } } return new RESTResponse(contentType, output, headers, httpStatus); }