Example usage for org.apache.http.client.fluent Request Get

List of usage examples for org.apache.http.client.fluent Request Get

Introduction

In this page you can find the example usage for org.apache.http.client.fluent Request Get.

Prototype

public static Request Get(final String uri) 

Source Link

Usage

From source file:org.schedulesdirect.api.json.DefaultJsonRequest.java

private Request initRequest() {
    Request r = null;/*from  ww  w  . j a v  a 2 s .c o  m*/
    switch (action) {
    case GET:
        r = Request.Get(baseUrl);
        break;
    case PUT:
        r = Request.Put(baseUrl);
        break;
    case POST:
        r = Request.Post(baseUrl);
        break;
    case DELETE:
        r = Request.Delete(baseUrl);
        break;
    case OPTIONS:
        r = Request.Options(baseUrl);
        break;
    case HEAD:
        r = Request.Head(baseUrl);
        break;
    }
    return r.userAgent(userAgent);
}

From source file:org.fuin.owndeb.commons.DebUtils.java

/**
 * Downloads a file from an URL to a file and outputs progress in the log
 * (level 'info') every 1000 bytes./*w  w  w . ja v a  2  s. c  o m*/
 * 
 * @param url
 *            URL to download.
 * @param dir
 *            Target directory.
 * @param cookies
 *            Cookies for the request (Format: "name=value").
 */
public static void download(@NotNull final URL url, @NotNull final File dir, final String... cookies) {
    Contract.requireArgNotNull("url", url);
    Contract.requireArgNotNull("dir", dir);

    LOG.info("Download: {}", url);

    try {
        final Request request = Request.Get(url.toURI());
        if (cookies != null) {
            final StringBuilder sb = new StringBuilder();
            for (int i = 0; i < cookies.length; i++) {
                if (i > 0) {
                    sb.append(";");
                }
                sb.append(cookies[i]);
            }
            request.addHeader("Cookie", sb.toString());
        }
        final File file = new File(dir, FilenameUtils.getName(url.getFile()));
        request.execute().saveContent(file);
    } catch (final IOException | URISyntaxException ex) {
        throw new RuntimeException("Error downloading: " + url, ex);
    }
}

From source file:com.qwazr.cluster.client.ClusterSingleClient.java

@Override
public ClusterServiceStatusJson getServiceStatus(String service_name, String group) {
    UBuilder uriBuilder = new UBuilder("/cluster/services/", service_name).setParameter("group", group);
    Request request = Request.Get(uriBuilder.build());
    return commonServiceRequest(request, null, null, ClusterServiceStatusJson.class, 200);
}

From source file:org.mule.module.http.functional.listener.HttpListenerLifecycleTestCase.java

@Test
public void restartListenerConfig() throws Exception {
    HttpListenerConfig httpListenerConfig = muleContext.getRegistry().get("testLifecycleListenerConfig");
    httpListenerConfig.stop();/* w  w w  .  ja  v a  2s . c  o m*/
    httpListenerConfig.start();
    final Response response = Request.Get(getLifecycleConfigUrl("/path/anotherPath")).execute();
    final HttpResponse httpResponse = response.returnResponse();
    assertThat(httpResponse.getStatusLine().getStatusCode(), is(200));
    assertThat(IOUtils.toString(httpResponse.getEntity().getContent()), is("catchAll"));
}

From source file:com.hack23.cia.service.external.common.impl.XmlAgentImpl.java

@Override
public Object unmarshallXml(final Unmarshaller unmarshaller, final String accessUrl, final String nameSpace,
        final String replace, final String with) throws Exception {

    LOGGER.info("Calls {}", accessUrl);

    final boolean isWeb = accessUrl.toLowerCase().startsWith("http://")
            || accessUrl.toLowerCase().startsWith("https://");

    String xmlContent;/*  w w  w. j a v  a  2s  . c  o m*/
    if (isWeb) {
        xmlContent = Request.Get(accessUrl.replace(" ", "")).execute().returnContent()
                .asString(StandardCharsets.UTF_8);
    } else {
        xmlContent = readInputStream(accessUrl.replace(" ", ""));
    }

    if (replace != null) {
        xmlContent = xmlContent.replace(replace, with);
    }

    final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
            xmlContent.getBytes(StandardCharsets.UTF_8));

    Source source;
    if (nameSpace != null) {
        source = setNameSpaceOnXmlStream(byteArrayInputStream, nameSpace);
    } else {
        source = new StreamSource(byteArrayInputStream);
    }

    return unmarshaller.unmarshal(source);
}

From source file:com.qwazr.scripts.ScriptSingleClient.java

@Override
public String getRunOut(String run_id, Boolean local, String group, Integer msTimeout) {
    try {//  w  ww.  j av a  2 s.  c  om
        UBuilder uriBuilder = new UBuilder(SCRIPT_PREFIX_STATUS, run_id, "/out").setParameters(local, group,
                msTimeout);
        Request request = Request.Get(uriBuilder.build());
        HttpResponse response = execute(request, null, null);
        return HttpUtils.checkTextPlainEntity(response, 200);
    } catch (HttpResponseEntityException e) {
        throw e.getWebApplicationException();
    } catch (IOException e) {
        throw new WebApplicationException(e.getMessage(), e, Status.INTERNAL_SERVER_ERROR);
    }
}

From source file:photosharing.api.conx.SearchPeopleDefinition.java

/**
 * searches for people// www  .  j  a  v  a 2 s.  c  om
 * 
 * @see photosharing.api.base.APIDefinition#run(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
public void run(HttpServletRequest request, HttpServletResponse response) {

    /**
     * check if query is empty, send SC_PRECONDITION_FAILED - 412
     */
    String query = request.getParameter("q");
    if (query == null || query.isEmpty()) {
        response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
    }

    /**
     * get the users bearer token
     */
    HttpSession session = request.getSession(false);
    OAuth20Data data = (OAuth20Data) session.getAttribute(OAuth20Handler.CREDENTIALS);
    String bearer = data.getAccessToken();

    /**
     * The query should be cleansed before passing it to the backend
     * 
     * Example API Url
     * http://localhost:9080/photoSharing/api/searchPeople?q=sub
     * maps to 
     * https://apps.collabservnext.com/search/oauth/people/typeahead?query=sub
     * 
     * Response Data
     * {
       *   "totalResults": 1,
       *   "startIndex": 1,
       *   "numResultsInCurrentPage": 1,
       *   "persons": [
      *      {
        *      "id": "20000397",
        *      "name": "John Doe2",
        *      "userType": "EMPLOYEE",
        *      "jobResponsibility": "Stooge",
        *      "confidence": "medium",
        *      "score": 10997.0
      *      }
       *   ]
     *   }
     * 
     */
    Request get = Request.Get(getApiUrl(query));
    get.addHeader("Authorization", "Bearer " + bearer);

    try {
        Executor exec = ExecutorUtil.getExecutor();
        Response apiResponse = exec.execute(get);
        HttpResponse hr = apiResponse.returnResponse();

        /**
         * Check the status codes
         */

        int code = hr.getStatusLine().getStatusCode();

        logger.info("Code is " + code + " " + getApiUrl(query));

        // Session is no longer valid or access token is expired
        if (code == HttpStatus.SC_FORBIDDEN) {
            response.sendRedirect("./api/logout");
        }

        // User is not authorized
        else if (code == HttpStatus.SC_UNAUTHORIZED) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        }

        // Content is returned
        else if (code == HttpStatus.SC_OK) {
            response.setStatus(HttpStatus.SC_OK);
            ServletOutputStream out = response.getOutputStream();
            InputStream in = hr.getEntity().getContent();
            IOUtils.copy(in, out);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }

        // Unexpected status
        else {
            JSONObject obj = new JSONObject();
            obj.put("error", "unexpected content");
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);

        }

    } catch (IOException e) {
        response.setHeader("X-Application-Error", e.getClass().getName());
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        logger.severe("IOException " + e.toString());
    } catch (JSONException e) {
        response.setHeader("X-Application-Error", e.getClass().getName());
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        logger.severe("JSONException " + e.toString());
    }

}

From source file:fi.ilmoeuro.membertrack.holvi.HolviPopulator.java

public void runPopulator() throws IOException {
    String url = String.format("https://holvi.com/api/checkout/v2/pool/%s/order/", config.getPoolHandle());
    while (url != null) {
        try (InputStream data = Request.Get(url)
                .setHeader("Authorization", String.format("Token %s", config.getAuthToken())).execute()
                .returnContent().asStream()) {
            OrdersResult orders = objectMapper.readValue(data, OrdersResult.class);
            handleOrders(orders);//w  w  w  . j a v  a  2 s  .  c om
            url = orders.getNext();
        }
    }
}

From source file:biz.dfch.j.clickatell.ClickatellClient.java

public CoverageResponse getCoverage(@NotNullable String recipient) throws URISyntaxException, IOException {
    URI uriCoverage = new URI(String.format(APICOVERAGE, recipient));
    String response = Request.Get(uriCoverage.toString()).setHeader(headerApiVersion)
            .setHeader(headerContentType).setHeader(headerAccept).setHeader("Authorization", bearerToken)
            .execute().returnContent().asString();

    ObjectMapper om = new ObjectMapper();
    om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, true);
    CoverageResponse coverageResponse = om.readValue(response, CoverageResponse.class);
    return coverageResponse;
}

From source file:org.mule.module.http.functional.proxy.HttpProxyTemplateTestCase.java

@Test
public void failIfTargetServiceIsDown() throws Exception {
    handlerExtender = null;//from  w w w  .j  ava 2  s . c o  m
    stopServer();
    Response response = Request.Get(getProxyUrl("")).connectTimeout(RECEIVE_TIMEOUT).execute();
    HttpResponse httpResponse = response.returnResponse();
    assertThat(httpResponse.getStatusLine().getStatusCode(), is(500));
}