List of usage examples for org.apache.http.client.fluent Request Get
public static Request Get(final String uri)
From source file:io.aos.protocol.http.httpcommon.FluentResponseHandling.java
public static void main(String... args) throws Exception { Document result = Request.Get("http://somehost/content").execute() .handleResponse(new ResponseHandler<Document>() { public Document handleResponse(final HttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); }//from ww w . j a va 2 s . c o m if (entity == null) { throw new ClientProtocolException("Response contains no content"); } DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); try { DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); ContentType contentType = ContentType.getOrDefault(entity); if (!contentType.equals(ContentType.APPLICATION_XML)) { throw new ClientProtocolException("Unexpected content type:" + contentType); } Charset charset = contentType.getCharset(); if (charset == null) { charset = HTTP.DEF_CONTENT_CHARSET; } return docBuilder.parse(entity.getContent(), charset.name()); } catch (ParserConfigurationException ex) { throw new IllegalStateException(ex); } catch (SAXException ex) { throw new ClientProtocolException("Malformed XML document", ex); } } }); // Do something useful with the result System.out.println(result); }
From source file:io.aos.protocol.http.httpcommon.FluentExecutor.java
public static void main(String... args) throws Exception { Executor executor = Executor.newInstance().auth(new HttpHost("somehost"), "username", "password") .auth(new HttpHost("myproxy", 8080), "username", "password") .authPreemptive(new HttpHost("myproxy", 8080)); // Execute a GET with timeout settings and return response content as String. executor.execute(Request.Get("http://somehost/").connectTimeout(1000).socketTimeout(1000)).returnContent() .asString();//w w w. j av a 2 s . c o m // Execute a POST with the 'expect-continue' handshake, using HTTP/1.1, // containing a request body as String and return response content as byte array. executor.execute(Request.Post("http://somehost/do-stuff").useExpectContinue().version(HttpVersion.HTTP_1_1) .bodyString("Important stuff", ContentType.DEFAULT_TEXT)).returnContent().asBytes(); // Execute a POST with a custom header through the proxy containing a request body // as an HTML form and save the result to the file executor.execute(Request.Post("http://somehost/some-form").addHeader("X-Custom-header", "stuff") .viaProxy(new HttpHost("myproxy", 8080)) .bodyForm(Form.form().add("username", "vip").add("password", "secret").build())) .saveContent(new File("result.dump")); }
From source file:com.mycompany.asyncreq.MainApp.java
public static void main(String[] args) throws InterruptedException, ExecutionException, IOException { URIBuilder builder = new URIBuilder(); builder.setScheme("http").setHost("comtrade.un.org").setPath("/api/get").setParameter("max", "50000") .setParameter("type", "C").setParameter("freq", "M").setParameter("px", "HS") .setParameter("ps", "2014").setParameter("r", "804").setParameter("p", "112") .setParameter("rg", "All").setParameter("cc", "All").setParameter("fmt", "json"); URI requestURL = null;/*from ww w .ja va2s . c om*/ try { requestURL = builder.build(); } catch (URISyntaxException use) { } ExecutorService threadpool = Executors.newFixedThreadPool(2); Async async = Async.newInstance().use(threadpool); final Request request = Request.Get(requestURL); try { Future<Content> future = async.execute(request, new FutureCallback<Content>() { @Override public void failed(final Exception e) { System.out.println(e.getMessage() + ": " + request); } @Override public void completed(final Content content) { System.out.println("Request completed: " + request); System.out.println("Response:\n" + content.asString()); } @Override public void cancelled() { } }); } catch (Exception e) { System.out.println("Job threw exception: " + e.getCause()); } }
From source file:com.phloc.html.supplementary.main.MainReadHTMLElementList.java
public static void main(final String[] args) throws Exception { s_aLogger.info("Extracting the information on all available HTML5 elements!"); s_aLogger.info("Reading HTML"); final byte[] aElementContent = Request.Get(BASE_URL + "elements.html").execute().returnContent().asBytes(); s_aLogger.info("Converting to XML"); final InputStream aIS = new NonBlockingByteArrayInputStream(aElementContent); final NonBlockingByteArrayOutputStream aOS = new NonBlockingByteArrayOutputStream(); final XmlSerializer serializer = new XmlSerializer(aOS); final HtmlParser parser = new HtmlParser(XmlViolationPolicy.ALTER_INFOSET); parser.setErrorHandler(LoggingSAXErrorHandler.getInstance()); parser.setContentHandler(serializer); parser.setLexicalHandler(serializer); parser.parse(new InputSource(aIS)); StreamUtils.close(aOS);//from w w w.j a v a 2 s .c o m s_aLogger.info("Converting to MicroNode"); final IMicroDocument aDoc = MicroReader.readMicroXML(aOS.toByteArray()); // /html/body/div[3]/div/ul final IMicroElement eUL = aDoc.getDocumentElement().getFirstChildElement(EHTMLElement.BODY) .getAllChildElements(EHTMLElement.DIV).get(2).getFirstChildElement(EHTMLElement.DIV) .getFirstChildElement(EHTMLElement.UL); final List<Element> aElements = new ArrayList<Element>(); for (final IMicroElement eLI : eUL.getAllChildElements(EHTMLElement.LI)) { final IMicroElement eA = eLI.getFirstChildElement(EHTMLElement.A); final String sHref = eA.getAttribute(CHTMLAttributes.HREF); final IMicroElement eSectionName = eA.getAllChildElements(EHTMLElement.SPAN).get(1); String sElementName = null; String sAttributeName = null; String sEqualsValue = null; String sShortDesc = null; for (final IMicroElement eSpan : eSectionName.getAllChildElements(EHTMLElement.SPAN)) { final String sClass = eSpan.getAttribute(CHTMLAttributes.CLASS); final String sContent = eSpan.getTextContent().trim(); if (sClass.equals("element")) sElementName = sContent; else if (sClass.equals("elem-qualifier")) { for (final IMicroElement eChildSpan : eSpan.getAllChildElements(EHTMLElement.SPAN)) { final String sChildClass = eChildSpan.getAttribute(CHTMLAttributes.CLASS); final String sChildContent = eChildSpan.getTextContent().trim(); if (sChildClass.equals("attribute-name")) sAttributeName = sChildContent; else if (sChildClass.equals("equals-value")) sEqualsValue = sChildContent; else s_aLogger.error("Illegal child span of '" + sElementName + "' with class '" + sChildClass + "'"); } } else if (sClass.equals("shortdesc")) sShortDesc = sContent; else s_aLogger.error("Illegal span in '" + sElementName + "' with class '" + sClass + "'"); } aElements.add(new Element(sHref, sElementName, sAttributeName, sEqualsValue, sShortDesc)); } s_aLogger.info("Writing result toc.xml"); final IMicroDocument aElementsDoc = new MicroDocument(); final IMicroElement eRoot = aElementsDoc.appendElement("elements"); for (final Element aElement : aElements) eRoot.appendChild(aElement.getAsMicroXML()); SimpleFileIO.writeFile(new File(PATH_TOC_XML), MicroWriter.getXMLString(aElementsDoc), XMLWriterSettings.DEFAULT_XML_CHARSET_OBJ); s_aLogger.info("Done"); }
From source file:com.lucas.analytics.controller.ml.SearchController.java
public static Search getSearch(String query) throws IOException { ObjectMapper mapper = new ObjectMapper(); String noWhitespace = query.replace(" ", "+"); String targetUrl = baseUrl + "?q=" + StringEscapeUtils.escapeHtml4(noWhitespace) + "&limit=10"; System.out.println("targetUrl: " + targetUrl); return mapper.readValue(Request.Get(targetUrl).execute().returnContent().asString(), Search.class); }
From source file:nl.rivm.cib.episim.cbs.CBSConnector.java
public static JsonNode getJSON(final String url) throws ClientProtocolException, IOException { return getJSON(Request.Get(url)); }
From source file:eu.anynet.java.util.HttpClient.java
/** * Create GET request//from w w w . ja v a 2 s.com * @param url The URL * @return The request */ public static Request Get(String url) { return defaults(Request.Get(url)); }
From source file:nl.rivm.cib.episim.cbs.CBSConnector.java
public static JsonNode getJSON(final URI url) throws ClientProtocolException, IOException { return getJSON(Request.Get(url)); }
From source file:org.wildfly.swarm.test.HelloEjbIT.java
@Test public void test() throws IOException { String response = Request.Get("http://localhost:8080/ejb").execute().returnContent().asString(); assertEquals("Hello from EJB\n", response); }
From source file:org.wildfly.swarm.test.HelloJaxrsIT.java
@Test public void test() throws IOException { String response = Request.Get("http://localhost:8080/jaxrs").execute().returnContent().asString(); assertEquals("Hello from JAX-RS", response); }