Example usage for org.apache.http.client.methods RequestBuilder get

List of usage examples for org.apache.http.client.methods RequestBuilder get

Introduction

In this page you can find the example usage for org.apache.http.client.methods RequestBuilder get.

Prototype

public static RequestBuilder get() 

Source Link

Usage

From source file:net.ymate.framework.commons.HttpClientHelper.java

public IHttpResponse get(String url, Map<String, String> params, Charset charset, Header[] headers,
        final String defaultResponseCharset) throws Exception {
    RequestBuilder _request = RequestBuilder.get().setUri(url).setCharset(charset);
    for (Map.Entry<String, String> entry : params.entrySet()) {
        _request.addParameter(entry.getKey(), entry.getValue());
    }/*from  w  ww .  j a  va 2  s.  c om*/
    if (headers != null && headers.length > 0) {
        for (Header _header : headers) {
            _request.addHeader(_header);
        }
    }
    CloseableHttpClient _httpClient = __doBuildHttpClient();
    try {
        return _httpClient.execute(_request.build(), new ResponseHandler<IHttpResponse>() {

            public IHttpResponse handleResponse(HttpResponse response) throws IOException {
                if (StringUtils.isNotBlank(defaultResponseCharset)) {
                    return new IHttpResponse.NEW(response, defaultResponseCharset);
                }
                return new IHttpResponse.NEW(response);
            }

        });
    } finally {
        _httpClient.close();
    }
}

From source file:org.dasein.cloud.azure.platform.AzureSQLDatabaseSupportRequests.java

public RequestBuilder listFirewallRules(String serveName) {
    RequestBuilder requestBuilder = RequestBuilder.get();
    addAzureCommonHeaders(requestBuilder);
    requestBuilder.setUri(//  www.  j  a  v  a 2  s.  c om
            String.format(RESOURCE_SERVER_FIREWALL, this.provider.getContext().getAccountNumber(), serveName));
    return requestBuilder;
}

From source file:edu.mit.scratch.Scratch.java

public static ScratchSession register(final String username, final String password, final String gender,
        final int birthMonth, final String birthYear, final String country, final String email)
        throws ScratchUserException {
    // Long if statement to verify all fields are valid
    if ((username.length() < 3) || (username.length() > 20) || (password.length() < 6) || (gender.length() < 2)
            || (birthMonth < 1) || (birthMonth > 12) || (birthYear.length() != 4) || (country.length() == 0)
            || (email.length() < 5)) {
        throw new ScratchUserException(); // TDL: Specify reason for failure
    } else {//from  w w  w .  ja v a  2  s. c om
        try {
            final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT)
                    .build();

            final CookieStore cookieStore = new BasicCookieStore();
            final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
            lang.setDomain(".scratch.mit.edu");
            lang.setPath("/");
            cookieStore.addCookie(lang);

            CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                    .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
            CloseableHttpResponse resp;

            final HttpUriRequest csrf = RequestBuilder.get().setUri("https://scratch.mit.edu/csrf_token/")
                    .addHeader("Accept", "*/*").addHeader("Referer", "https://scratch.mit.edu")
                    .addHeader("X-Requested-With", "XMLHttpRequest").build();
            try {
                resp = httpClient.execute(csrf);
            } catch (final IOException e) {
                e.printStackTrace();
                throw new ScratchUserException();
            }
            try {
                resp.close();
            } catch (final IOException e) {
                throw new ScratchUserException();
            }

            String csrfToken = null;
            for (final Cookie c : cookieStore.getCookies())
                if (c.getName().equals("scratchcsrftoken"))
                    csrfToken = c.getValue();

            /*
             * try {
             * username = URLEncoder.encode(username, "UTF-8");
             * password = URLEncoder.encode(password, "UTF-8");
             * birthMonth = Integer.parseInt(URLEncoder.encode("" +
             * birthMonth, "UTF-8"));
             * birthYear = URLEncoder.encode(birthYear, "UTF-8");
             * gender = URLEncoder.encode(gender, "UTF-8");
             * country = URLEncoder.encode(country, "UTF-8");
             * email = URLEncoder.encode(email, "UTF-8");
             * } catch (UnsupportedEncodingException e1) {
             * e1.printStackTrace();
             * }
             */

            final BasicClientCookie csrfCookie = new BasicClientCookie("scratchcsrftoken", csrfToken);
            csrfCookie.setDomain(".scratch.mit.edu");
            csrfCookie.setPath("/");
            cookieStore.addCookie(csrfCookie);
            final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
            debug.setDomain(".scratch.mit.edu");
            debug.setPath("/");
            cookieStore.addCookie(debug);

            httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                    .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();

            /*
             * final String data = "username=" + username + "&password=" +
             * password + "&birth_month=" + birthMonth + "&birth_year=" +
             * birthYear + "&gender=" + gender + "&country=" + country +
             * "&email=" + email +
             * "&is_robot=false&should_generate_admin_ticket=false&usernames_and_messages=%3Ctable+class%3D'banhistory'%3E%0A++++%3Cthead%3E%0A++++++++%3Ctr%3E%0A++++++++++++%3Ctd%3EAccount%3C%2Ftd%3E%0A++++++++++++%3Ctd%3EEmail%3C%2Ftd%3E%0A++++++++++++%3Ctd%3EReason%3C%2Ftd%3E%0A++++++++++++%3Ctd%3EDate%3C%2Ftd%3E%0A++++++++%3C%2Ftr%3E%0A++++%3C%2Fthead%3E%0A++++%0A%3C%2Ftable%3E%0A&csrfmiddlewaretoken="
             * + csrfToken;
             * System.out.println(data);
             */

            final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addTextBody("birth_month", birthMonth + "", ContentType.TEXT_PLAIN);
            builder.addTextBody("birth_year", birthYear, ContentType.TEXT_PLAIN);
            builder.addTextBody("country", country, ContentType.TEXT_PLAIN);
            builder.addTextBody("csrfmiddlewaretoken", csrfToken, ContentType.TEXT_PLAIN);
            builder.addTextBody("email", email, ContentType.TEXT_PLAIN);
            builder.addTextBody("gender", gender, ContentType.TEXT_PLAIN);
            builder.addTextBody("is_robot", "false", ContentType.TEXT_PLAIN);
            builder.addTextBody("password", password, ContentType.TEXT_PLAIN);
            builder.addTextBody("should_generate_admin_ticket", "false", ContentType.TEXT_PLAIN);
            builder.addTextBody("username", username, ContentType.TEXT_PLAIN);
            builder.addTextBody("usernames_and_messages",
                    "<table class=\"banhistory\"> <thead> <tr> <td>Account</td> <td>Email</td> <td>Reason</td> <td>Date</td> </tr> </thead> </table>",
                    ContentType.TEXT_PLAIN);

            final HttpUriRequest createAccount = RequestBuilder.post()
                    .setUri("https://scratch.mit.edu/accounts/register_new_user/")
                    .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
                    .addHeader("Referer", "https://scratch.mit.edu/accounts/standalone-registration/")
                    .addHeader("Origin", "https://scratch.mit.edu")
                    .addHeader("Accept-Encoding", "gzip, deflate").addHeader("DNT", "1")
                    .addHeader("Accept-Language", "en-US,en;q=0.8")
                    .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                    .addHeader("X-Requested-With", "XMLHttpRequest").addHeader("X-CSRFToken", csrfToken)
                    .addHeader("X-DevTools-Emulate-Network-Conditions-Client-Id",
                            "54255D9A-9771-4CAC-9052-50C8AB7469E0")
                    .setEntity(builder.build()).build();
            resp = httpClient.execute(createAccount);
            System.out.println("REGISTER:" + resp.getStatusLine());
            final BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));

            final StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null)
                result.append(line);
            System.out.println("exact:" + result.toString() + "\n" + resp.getStatusLine().getReasonPhrase()
                    + "\n" + resp.getStatusLine());
            if (resp.getStatusLine().getStatusCode() != 200)
                throw new ScratchUserException();
            resp.close();
        } catch (final Exception e) {
            e.printStackTrace();
            throw new ScratchUserException();
        }
        try {
            return Scratch.createSession(username, password);
        } catch (final Exception e) {
            e.printStackTrace();
            throw new ScratchUserException();
        }
    }
}

From source file:jp.classmethod.aws.brian.BrianClient.java

@Override
public List<String> listTriggers(String group) throws BrianClientException, BrianServerException {
    logger.debug("list triggers: {}", group);
    HttpResponse httpResponse = null;/*  w  w w.ja v a  2s .com*/
    try {
        String path = String.format("/triggers/%s", group);
        URI uri = new URI(scheme, null, hostname, port, path, null, null);
        HttpUriRequest httpRequest = RequestBuilder.get().setUri(uri).build();
        httpResponse = httpClientExecute(httpRequest);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        logger.debug("statusCode: {}", statusCode);
        if (statusCode == HttpStatus.SC_OK) {
            JsonNode tree = mapper.readTree(httpResponse.getEntity().getContent());
            return StreamSupport.stream(tree.spliterator(), false).map(item -> item.textValue())
                    .collect(Collectors.toList());
        } else if (statusCode >= 500) {
            throw new BrianServerException("status = " + statusCode);
        } else if (statusCode >= 400) {
            throw new BrianClientException("status = " + statusCode);
        } else {
            throw new Error("status = " + statusCode);
        }
    } catch (URISyntaxException e) {
        throw new IllegalStateException(e);
    } catch (IOException e) {
        throw new BrianServerException(e);
    } catch (IllegalStateException e) {
        throw new Error(e);
    } finally {
        if (httpResponse != null) {
            EntityUtils.consumeQuietly(httpResponse.getEntity());
        }
    }
}

From source file:com.vmware.gemfire.tools.pulse.tests.junit.BaseServiceTest.java

/**
*
* Tests that service returns json object
*
* Test method for {@link com.vmware.gemfire.tools.pulse.internal.service.ClusterSelectedRegionService#execute(javax.servlet.http.HttpServletRequest)}.
*///  w  ww .  ja  v a  2s  . c  om
@Test
public void testServerLoginLogout() {
    System.out.println("BaseServiceTest ::  ------TESTCASE BEGIN : SERVER LOGIN-LOGOUT------");
    try {
        doLogin();

        HttpUriRequest pulseupdate = RequestBuilder.get().setUri(new URI(IS_AUTHENTICATED_USER_URL)).build();
        CloseableHttpResponse response = httpclient.execute(pulseupdate);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("BaseServiceTest :: HTTP request status : " + response.getStatusLine());

            BufferedReader respReader = new BufferedReader(new InputStreamReader(entity.getContent()));
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            String sz = null;
            while ((sz = respReader.readLine()) != null) {
                pw.print(sz);
            }
            String jsonResp = sw.getBuffer().toString();
            System.out.println("BaseServiceTest :: JSON response returned : " + jsonResp);
            EntityUtils.consume(entity);

            JsonNode jsonObj = mapper.readTree(jsonResp);
            boolean isUserLoggedIn = jsonObj.get("isUserLoggedIn").booleanValue();
            Assert.assertNotNull("BaseServiceTest :: Server returned null response in 'isUserLoggedIn'",
                    isUserLoggedIn);
            Assert.assertTrue("BaseServiceTest :: User login failed for this username, password",
                    (isUserLoggedIn == true));
        } finally {
            response.close();
        }

        doLogout();
    } catch (Exception failed) {
        logException(failed);
        Assert.fail("Exception ! ");
    }
    System.out.println("BaseServiceTest ::  ------TESTCASE END : SERVER LOGIN-LOGOUT------");
}

From source file:com.searchbox.collection.oppfin.IdealISTCollection.java

public ItemReader<String> reader() {
    return new ItemReader<String>() {

        List<String> documents;
        int page = 0;

        {//from   w w w  . j av a2 s.  c  om
            documents = new ArrayList<String>();
        }

        @Override
        public String read() {

            if (documents.isEmpty()) {
                Document xmlDocuments = httpGet(RequestBuilder.get()
                        .setUri(env.getProperty(IDEALIST_LIST_SERVICE, IDEALIST_LIST_SERVICE_DEFAULT))
                        .addParameter("pageNum", Integer.toString(page)).addParameter("pageSize", "10"));
                NodeList documentList = xmlDocuments.getElementsByTagName("document");
                for (int i = 0; i < documentList.getLength(); i++) {
                    String uid = documentList.item(i).getAttributes().getNamedItem("uid").getNodeValue();
                    documents.add(uid);
                }

                page++;
            }

            if (documents.isEmpty()) {
                return null;
            } else {
                return documents.remove(0);
            }
        }
    };
}

From source file:fi.okm.mpass.shibboleth.attribute.resolver.dc.impl.RestDataConnector.java

/** {@inheritDoc} */
@Nullable//from w  w  w .  ja  va 2 s .c  o  m
@Override
protected Map<String, IdPAttribute> doDataConnectorResolve(
        @Nonnull final AttributeResolutionContext attributeResolutionContext,
        @Nonnull final AttributeResolverWorkContext attributeResolverWorkContext) throws ResolutionException {
    final Map<String, IdPAttribute> attributes = new HashMap<>();

    log.debug("Calling {} for resolving attributes", endpointUrl);

    String authnIdValue = collectSingleAttributeValue(
            attributeResolverWorkContext.getResolvedIdPAttributeDefinitions(), hookAttribute);
    log.debug("AuthnID before URL encoding = {}", authnIdValue);
    if (authnIdValue == null) {
        log.error("Could not resolve hookAttribute value");
        throw new ResolutionException("Could not resolve hookAttribute value");
    }
    try {
        authnIdValue = URLEncoder.encode(collectSingleAttributeValue(
                attributeResolverWorkContext.getResolvedIdPAttributeDefinitions(), hookAttribute), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        log.error("Could not use UTF-8 for encoding authnID");
        throw new ResolutionException("Could not use UTF-8 for encoding authnID", e);
    }
    log.debug("AuthnID after URL encoding = {}", authnIdValue);
    final String idpIdValue = collectSingleAttributeValue(
            attributeResolverWorkContext.getResolvedIdPAttributeDefinitions(), idpId);
    if (StringSupport.trimOrNull(idpIdValue) == null) {
        log.error("Could not resolve idpId value");
        throw new ResolutionException("Could not resolve idpId value");
    }
    final String attributeCallUrl = endpointUrl + "?" + idpIdValue + "=" + authnIdValue;

    final HttpClient httpClient;
    try {
        httpClient = buildClient();
    } catch (Exception e) {
        log.error("Could not build HTTP client, skipping attribute resolution", e);
        return attributes;
    }
    log.debug("Calling URL {}", attributeCallUrl);
    final HttpContext context = HttpClientContext.create();
    final HttpUriRequest getMethod = RequestBuilder.get().setUri(attributeCallUrl)
            .setHeader("Authorization", "Token " + token).build();
    final HttpResponse restResponse;
    final long timestamp = System.currentTimeMillis();
    try {
        restResponse = httpClient.execute(getMethod, context);
    } catch (Exception e) {
        log.error("Could not open connection to REST API, skipping attribute resolution", e);
        return attributes;
    }

    final int status = restResponse.getStatusLine().getStatusCode();
    log.info("API call took {} ms, response code {}", System.currentTimeMillis() - timestamp, status);

    if (log.isTraceEnabled()) {
        if (restResponse.getAllHeaders() != null) {
            for (Header header : restResponse.getAllHeaders()) {
                log.trace("Header {}: {}", header.getName(), header.getValue());
            }
        }
    }

    try {
        final String restResponseStr = EntityUtils.toString(restResponse.getEntity(), "UTF-8");
        log.trace("Response {}", restResponseStr);
        if (status == HttpStatus.SC_OK) {
            final Gson gson = new Gson();
            final UserDTO ecaUser = gson.fromJson(restResponseStr, UserDTO.class);
            populateAttributes(attributes, ecaUser);
            log.debug("{} attributes are now populated", attributes.size());
        } else {
            log.warn("No attributes found for session with idpId {}, http status {}", idpIdValue, status);
        }
    } catch (Exception e) {
        log.error("Error in connection to Data API", e);
    } finally {
        EntityUtils.consumeQuietly(restResponse.getEntity());
    }
    return attributes;
}

From source file:edu.mit.scratch.ScratchCloudSession.java

public String get(final String key) throws ScratchProjectException {
    try {//w w w  .jav  a  2  s.  co m
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        lang.setDomain(".scratch.mit.edu");
        lang.setPath("/");
        cookieStore.addCookie(lang);

        final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse resp;

        final HttpUriRequest update = RequestBuilder.get()
                .setUri("https://scratch.mit.edu/varserver/" + this.getProjectID())
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*//*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu")
                .addHeader("Accept-Encoding", "gzip, deflate, sdch")
                .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json")
                .addHeader("X-Requested-With", "XMLHttpRequest").build();
        try {
            resp = httpClient.execute(update);
        } catch (final IOException e) {
            e.printStackTrace();
            throw new ScratchProjectException();
        }

        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        } catch (UnsupportedOperationException | IOException e) {
            e.printStackTrace();
            throw new ScratchProjectException();
        }

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        final JSONObject jsonOBJ = new JSONObject(result.toString().trim());

        final Iterator<?> keys = ((JSONArray) jsonOBJ.get("variables")).iterator();

        while (keys.hasNext()) {
            final JSONObject o = new JSONObject(StringEscapeUtils.unescapeJson("" + keys.next()));
            final String k = o.get("name") + "";

            if (k.equals(key))
                return o.get("value") + "";
        }
    } catch (final Exception e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }

    return null;
}

From source file:com.baidu.rigel.biplatform.ac.util.HttpRequest.java

/**
 * ?URL??GET//from   w ww.  j  ava2  s . c  om
 * 
 * @param client httpclient
 * @param url ??URL
 * @param param ?? name1=value1&name2=value2 ?
 * @return URL ??
 */
public static String sendGet(HttpClient client, String url, Map<String, String> params) {
    if (client == null || StringUtils.isBlank(url)) {
        throw new IllegalArgumentException("client is null");
    }
    if (params == null) {
        params = new HashMap<String, String>(1);
    }

    String newUrl = processPlaceHolder(url, params);
    String cookie = params.remove(COOKIE_PARAM_NAME);

    List<String> paramList = checkUrlAndWrapParam(newUrl, params, true);
    String urlNameString = "";
    if (newUrl.contains("?")) {
        paramList.add(0, newUrl);
        urlNameString = StringUtils.join(paramList, "&");
    } else {
        urlNameString = newUrl + "?" + StringUtils.join(paramList, "&");
    }

    String prefix = "", suffix = "";
    String[] addresses = new String[] { urlNameString };
    if (urlNameString.contains("[") && urlNameString.contains("]")) {
        addresses = urlNameString.substring(urlNameString.indexOf("[") + 1, urlNameString.indexOf("]"))
                .split(" ");
        prefix = urlNameString.substring(0, urlNameString.indexOf("["));
        suffix = urlNameString.substring(urlNameString.indexOf("]") + 1);
    }
    LOGGER.info("start to send get:" + urlNameString);
    long current = System.currentTimeMillis();
    Exception ex = null;
    for (String address : addresses) {
        String requestUrl = prefix + address + suffix;
        try {
            HttpUriRequest request = RequestBuilder.get().setUri(requestUrl).build();

            if (StringUtils.isNotBlank(cookie)) {
                // ?cookie
                request.addHeader(new BasicHeader(COOKIE_PARAM_NAME, cookie));
            }
            HttpResponse response = client.execute(request);
            String content = processHttpResponse(client, response, params, true);
            LOGGER.info("end send get :" + urlNameString + " cost:" + (System.currentTimeMillis() - current));
            return content;
        } catch (Exception e) {
            ex = e;
            LOGGER.warn("send get error " + requestUrl + ",retry next one", e);
        }
    }
    throw new RuntimeException(ex);
}

From source file:edu.mit.scratch.ScratchUser.java

public int getMessageCount() throws ScratchUserException {
    try {/*w  w w  .  j  a va 2  s. c om*/
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
        debug.setDomain(".scratch.mit.edu");
        debug.setPath("/");
        lang.setPath("/");
        lang.setDomain(".scratch.mit.edu");
        cookieStore.addCookie(lang);
        cookieStore.addCookie(debug);

        final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse resp;

        final HttpUriRequest update = RequestBuilder.get()
                .setUri("https://api.scratch.mit.edu/users/" + this.getUsername() + "/messages/count")
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu/users/" + this.getUsername() + "/")
                .addHeader("Origin", "https://scratch.mit.edu")
                .addHeader("Accept-Encoding", "gzip, deflate, sdch")
                .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json")
                .addHeader("X-Requested-With", "XMLHttpRequest").build();
        try {
            resp = httpClient.execute(update);
        } catch (final IOException e) {
            e.printStackTrace();
            throw new ScratchUserException();
        }

        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        } catch (UnsupportedOperationException | IOException e) {
            e.printStackTrace();
            throw new ScratchUserException();
        }

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        final JSONObject jsonOBJ2 = new JSONObject(result.toString().trim());

        return jsonOBJ2.getInt("count");
    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new ScratchUserException();
    } catch (final Exception e) {
        e.printStackTrace();
        throw new ScratchUserException();
    }
}