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.platform.module.wechat.support.HttpClientHelper.java

public String doGet(String url) throws Exception {
    CloseableHttpClient _httpClient = __doBuildHttpClient();
    try {//ww  w  . j  av a 2s  . c  o  m
        _LOG.debug("Request URL [" + url + "]");
        String _result = _httpClient.execute(RequestBuilder.get().setUri(url).build(),
                new ResponseHandler<String>() {

                    public String handleResponse(HttpResponse response) throws IOException {
                        return EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);
                    }

                });
        _LOG.debug("Request URL [" + url + "] Response [" + _result + "]");
        return _result;
    } finally {
        _httpClient.close();
    }
}

From source file:org.jmonkey.external.bintray.BintrayApiClient.java

public String getPackageReadme(String packageName) throws IOException {

    try (CloseableHttpClient httpClient = this.createClient()) {

        HttpUriRequest request = RequestBuilder.get().setUri("https://api.bintray.com/packages/"
                + config.getSubject() + "/" + config.getRepo() + "/" + this.cleanQuery(packageName) + "/readme")
                .build();// w ww.  j a v  a  2  s.co  m

        try (CloseableHttpResponse httpResponse = httpClient.execute(request)) {

            int statusCode = httpResponse.getStatusLine().getStatusCode();

            if (statusCode >= 400) {
                // @TODO: provide a consumable error
            }

            HttpEntity entity = httpResponse.getEntity();
            String entityString = EntityUtils.toString(entity);
            EntityUtils.consume(entity);

            Map<Object, Object> result = JmeResourceWebsite.getObjectMapper().readValue(entityString,
                    new TypeReference<Map<Object, Object>>() {
                    });

            // https://bintray.com/docs/api/#_get_readme

            String noReadmeFound = "this package does not contain a readme.";

            if (result == null || result.isEmpty()) {
                return noReadmeFound;
            }

            if (result.get("message") != null) {
                return noReadmeFound;
            }

            if (result.get("bintray") != null) {

                @SuppressWarnings("unchecked")
                Map<String, String> bintrayData = (Map<String, String>) result.get("bintray");

                if (bintrayData.get("content") == null) {
                    return noReadmeFound;
                }

                return bintrayData.get("content");
            }

            if (result.containsKey("github")) {

                @SuppressWarnings("unchecked")
                Map<String, String> githubData = (Map<String, String>) result.get("github");

                if (githubData.get("github_repo") == null) {
                    return noReadmeFound;
                }

                return "github readme.";
            }

            return noReadmeFound;
        }
    }

}

From source file:cf.spring.servicebroker.CatalogTest.java

@Test
public void goodAuthentication() throws Exception {
    final SpringApplication application = new SpringApplication(EmptyServiceBrokerCatalog.class);
    try (ConfigurableApplicationContext context = application.run();
            CloseableHttpClient client = buildAuthenticatingClient()) {
        final HttpUriRequest catalogRequest = RequestBuilder.get()
                .setUri("http://localhost:8080" + Constants.CATALOG_URI).build();
        final CloseableHttpResponse response = client.execute(catalogRequest);
        assertEquals(response.getStatusLine().getStatusCode(), 200);
    }//  ww  w. j a va2  s  .  com
}

From source file:edu.usu.sdl.apiclient.AbstractService.java

protected void logon() {
    //get the initial cookies
    HttpGet httpget = new HttpGet(loginModel.getServerUrl());
    try (CloseableHttpResponse response = httpclient.execute(httpget)) {
        HttpEntity entity = response.getEntity();

        log.log(Level.FINE, "Login form get: {0}", response.getStatusLine());
        EntityUtils.consume(entity);/*from w  ww  . j  av a 2s .  c o  m*/

        log.log(Level.FINEST, "Initial set of cookies:");
        List<Cookie> cookies = cookieStore.getCookies();
        if (cookies.isEmpty()) {
            log.log(Level.FINEST, "None");
        } else {
            for (Cookie cookie : cookies) {
                log.log(Level.FINEST, "- {0}", cookie.toString());
            }
        }
    } catch (IOException ex) {
        throw new ConnectionException("Unable to Connect.", ex);
    }

    //login
    try {
        HttpUriRequest login = RequestBuilder.post().setUri(new URI(loginModel.getSecurityUrl()))
                .addParameter(loginModel.getUsernameField(), loginModel.getUsername())
                .addParameter(loginModel.getPasswordField(), loginModel.getPassword()).build();
        try (CloseableHttpResponse response = httpclient.execute(login)) {
            HttpEntity entity = response.getEntity();

            log.log(Level.FINE, "Login form get: {0}", response.getStatusLine());
            EntityUtils.consume(entity);

            log.log(Level.FINEST, "Post logon cookies:");
            List<Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
                log.log(Level.FINEST, "None");
            } else {
                for (Cookie cookie : cookies) {
                    log.log(Level.FINEST, "- {0}", cookie.toString());
                }
            }
        }

        //For some reason production requires getting the first page first
        RequestConfig defaultRequestConfig = RequestConfig.custom().setCircularRedirectsAllowed(true).build();

        HttpUriRequest data = RequestBuilder.get().setUri(new URI(loginModel.getServerUrl()))
                .addHeader(CONTENT_TYPE, MEDIA_TYPE_JSON).setConfig(defaultRequestConfig).build();

        try (CloseableHttpResponse response = httpclient.execute(data)) {
            log.log(Level.FINE, "Response Status from connection: {0}  {1}", new Object[] {
                    response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase() });
            HttpEntity entity1 = response.getEntity();
            EntityUtils.consume(entity1);
        }

    } catch (IOException | URISyntaxException ex) {
        throw new ConnectionException("Unable to login.", ex);
    }
}

From source file:com.esri.geoevent.test.performance.provision.GeoEventProvisioner.java

private void resetConfiguration() throws IOException {
    System.out.print(ImplMessages.getMessage("PROVISIONER_RESETTING_CONFIG_MSG"));
    String url = "https://" + hostName + ":" + 6143 + "/geoevent/admin/configuration/reset/.json";

    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(getSSLSocketFactory()).build();
    HttpUriRequest request = RequestBuilder.get().setUri(url).addParameter("token", token)
            .addHeader("referer", referer).build();

    HttpResponse response = httpClient.execute(request);
    HttpEntity entity = response.getEntity();
    ObjectMapper mapper = new ObjectMapper();
    @SuppressWarnings("unused")
    JsonNode jsonResponse = mapper.readTree(entity.getContent());
    sleep(10 * 1000);//from w  w w.  ja v  a2s.  c o m
    System.out.println(ImplMessages.getMessage("DONE"));
}

From source file:net.ymate.platform.module.wechat.support.HttpClientHelper.java

public String doGet(String url, Map<String, String> params) throws Exception {
    RequestBuilder _request = RequestBuilder.get().setUri(url);
    for (Map.Entry<String, String> entry : params.entrySet()) {
        _request.addParameter(entry.getKey(), entry.getValue());
    }/*from   w w  w  .j  a  v a 2  s . co  m*/
    CloseableHttpClient _httpClient = __doBuildHttpClient();
    try {
        _LOG.debug("Request URL [" + url + "], Param [" + params + "]");
        String _result = _httpClient.execute(_request.build(), new ResponseHandler<String>() {

            public String handleResponse(HttpResponse response) throws IOException {
                return EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);
            }

        });
        _LOG.debug("Request URL [" + url + "] Response [" + _result + "]");
        return _result;
    } finally {
        _httpClient.close();
    }
}

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

public RequestBuilder listDatabases(String serverName) {
    RequestBuilder requestBuilder = RequestBuilder.get();
    addAzureCommonHeaders(requestBuilder);
    requestBuilder.setUri(// w  ww.j a v a  2 s  .  c  o  m
            String.format(RESOURCE_LIST_DATABASES, this.provider.getContext().getAccountNumber(), serverName));
    return requestBuilder;
}

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

public ScratchUserManager update() throws ScratchUserException {
    try {// w  w  w  .  j ava 2  s  .  c  o  m
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        final BasicClientCookie sessid = new BasicClientCookie("scratchsessionsid",
                this.session.getSessionID());
        final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", this.session.getCSRFToken());
        final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
        lang.setDomain(".scratch.mit.edu");
        lang.setPath("/");
        sessid.setDomain(".scratch.mit.edu");
        sessid.setPath("/");
        token.setDomain(".scratch.mit.edu");
        token.setPath("/");
        debug.setDomain(".scratch.mit.edu");
        debug.setPath("/");
        cookieStore.addCookie(lang);
        cookieStore.addCookie(sessid);
        cookieStore.addCookie(token);
        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://scratch.mit.edu/messages/ajax/get-message-count/")
                .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")
                .addHeader("Cookie",
                        "scratchsessionsid=" + this.session.getSessionID() + "; scratchcsrftoken="
                                + this.session.getCSRFToken())
                .addHeader("X-CSRFToken", this.session.getCSRFToken()).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 jsonOBJ = new JSONObject(result.toString().trim());

        final Iterator<?> keys = jsonOBJ.keys();

        while (keys.hasNext()) {
            final String key = "" + keys.next();
            final Object o = jsonOBJ.get(key);
            final String val = "" + o;

            switch (key) {
            case "msg_count":
                this.message_count = Integer.parseInt(val);
                break;
            default:
                System.out.println("Missing reference:" + key);
                break;
            }
        }
    } catch (final Exception e) {
        e.printStackTrace();
        throw new ScratchUserException();
    }

    return this;
}

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

@Override
public boolean isAvailable() {
    logger.debug("is available?");
    HttpResponse httpResponse = null;/*from   w  ww.ja  v  a  2s  .  com*/
    try {
        URI uri = new URI(scheme, null, hostname, port, "/", null, null);
        HttpUriRequest httpRequest = RequestBuilder.get().setUri(uri).build();
        httpResponse = httpClientExecute(httpRequest);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        logger.debug("statusCode: {}", statusCode);
        return statusCode == HttpStatus.SC_OK;
    } catch (Exception e) {
        logger.warn("{}: {}", e.getClass().getName(), e.getMessage());
    } finally {
        if (httpResponse != null) {
            EntityUtils.consumeQuietly(httpResponse.getEntity());
        }
    }
    return false;
}

From source file:nya.miku.wishmaster.http.streamer.HttpStreamer.java

/**
 * HTTP ?  ?. ? ?  ? ?,    release()  !//from www  .j  a  v  a 2  s .  c o  m
 * ?   ? ?? ? ?  If-Modified-Since,  ?      
 *  ? ?? ?    Modified ({@link #removeFromModifiedMap(String)})!
 * @param url ? ?
 * @param requestModel  ? (  null,   GET   If-Modified)
 * @param httpClient HTTP , ?? ?
 * @param listener ? ?? ?? (  null)
 * @param task ,     (  null)
 * @return  ?     HTTP 
 * @throws HttpRequestException ?, ?  ?  ?
 */
public HttpResponseModel getFromUrl(String url, HttpRequestModel requestModel, HttpClient httpClient,
        ProgressListener listener, CancellableTask task) throws HttpRequestException {
    if (requestModel == null)
        requestModel = HttpRequestModel.builder().setGET().build();

    // Request
    HttpUriRequest request = null;
    try {
        RequestConfig requestConfigBuilder = ExtendedHttpClient
                .getDefaultRequestConfigBuilder(requestModel.timeoutValue)
                .setRedirectsEnabled(!requestModel.noRedirect).build();

        RequestBuilder requestBuilder = null;
        switch (requestModel.method) {
        case HttpRequestModel.METHOD_GET:
            requestBuilder = RequestBuilder.get().setUri(url);
            break;
        case HttpRequestModel.METHOD_POST:
            requestBuilder = RequestBuilder.post().setUri(url).setEntity(requestModel.postEntity);
            break;
        default:
            throw new IllegalArgumentException("Incorrect type of HTTP Request");
        }
        if (requestModel.customHeaders != null) {
            for (Header header : requestModel.customHeaders) {
                requestBuilder.addHeader(header);
            }
        }
        if (requestModel.checkIfModified && requestModel.method == HttpRequestModel.METHOD_GET) {
            synchronized (ifModifiedMap) {
                if (ifModifiedMap.containsKey(url)) {
                    requestBuilder
                            .addHeader(new BasicHeader(HttpHeaders.IF_MODIFIED_SINCE, ifModifiedMap.get(url)));
                }
            }
        }
        request = requestBuilder.setConfig(requestConfigBuilder).build();
    } catch (Exception e) {
        Logger.e(TAG, e);
        HttpResponseModel.release(request, null);
        throw new IllegalArgumentException(e);
    }
    // ?
    HttpResponseModel responseModel = new HttpResponseModel();
    HttpResponse response = null;
    try {
        IOException responseException = null;
        for (int i = 0; i < 5; ++i) {
            try {
                if (task != null && task.isCancelled())
                    throw new InterruptedException();
                response = httpClient.execute(request);
                responseException = null;
                break;
            } catch (IOException e) {
                Logger.e(TAG, e);
                responseException = e;
                if (e.getMessage() == null)
                    break;
                if (e.getMessage().indexOf("Connection reset by peer") != -1
                        || e.getMessage().indexOf("I/O error during system call, Broken pipe") != -1) {
                    continue;
                } else {
                    break;
                }
            }
        }
        if (responseException != null) {
            throw responseException;
        }
        if (task != null && task.isCancelled())
            throw new InterruptedException();
        //  ???? HTTP
        StatusLine status = response.getStatusLine();
        responseModel.statusCode = status.getStatusCode();
        responseModel.statusReason = status.getReasonPhrase();
        //   (headers)
        String lastModifiedValue = null;
        if (responseModel.statusCode == 200) {
            Header header = response.getFirstHeader(HttpHeaders.LAST_MODIFIED);
            if (header != null)
                lastModifiedValue = header.getValue();
        }
        Header header = response.getFirstHeader(HttpHeaders.LOCATION);
        if (header != null)
            responseModel.locationHeader = header.getValue();
        responseModel.headers = response.getAllHeaders();
        //
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            responseModel.contentLength = responseEntity.getContentLength();
            if (listener != null)
                listener.setMaxValue(responseModel.contentLength);
            InputStream stream = responseEntity.getContent();
            responseModel.stream = IOUtils.modifyInputStream(stream, listener, task);
        }
        responseModel.request = request;
        responseModel.response = response;
        if (lastModifiedValue != null) {
            synchronized (ifModifiedMap) {
                ifModifiedMap.put(url, lastModifiedValue);
            }
        }
    } catch (Exception e) {
        Logger.e(TAG, e);
        HttpResponseModel.release(request, response);
        throw new HttpRequestException(e);
    }

    return responseModel;
}