Example usage for org.apache.http.impl.client CloseableHttpClient execute

List of usage examples for org.apache.http.impl.client CloseableHttpClient execute

Introduction

In this page you can find the example usage for org.apache.http.impl.client CloseableHttpClient execute.

Prototype

public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException 

Source Link

Usage

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

public static ScratchSession createSession(final String username, String password)
        throws ScratchLoginException {
    try {//from   www  .j  a v a 2  s  . c o m
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT) // Changed due to deprecation
                .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 csrf = RequestBuilder.get().setUri("https://scratch.mit.edu/csrf_token/")
                .addHeader("Accept", "*/*").addHeader("Referer", "https://scratch.mit.edu")
                .addHeader("X-Requested-With", "XMLHttpRequest").build();
        resp = httpClient.execute(csrf);
        resp.close();

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

        final JSONObject loginObj = new JSONObject();
        loginObj.put("username", username);
        loginObj.put("password", password);
        loginObj.put("captcha_challenge", "");
        loginObj.put("captcha_response", "");
        loginObj.put("embed_captcha", false);
        loginObj.put("timezone", "America/New_York");
        loginObj.put("csrfmiddlewaretoken", csrfToken);
        final HttpUriRequest login = RequestBuilder.post().setUri("https://scratch.mit.edu/accounts/login/")
                .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
                .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu")
                .addHeader("Accept-Encoding", "gzip, deflate").addHeader("Accept-Language", "en-US,en;q=0.8")
                .addHeader("Content-Type", "application/json").addHeader("X-Requested-With", "XMLHttpRequest")
                .addHeader("X-CSRFToken", csrfToken).setEntity(new StringEntity(loginObj.toString())).build();
        resp = httpClient.execute(login);
        password = null;
        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);
        final JSONObject jsonOBJ = new JSONObject(
                result.toString().substring(1, result.toString().length() - 1));
        if ((int) jsonOBJ.get("success") != 1)
            throw new ScratchLoginException();
        String ssi = null;
        String sct = null;
        String e = null;
        final Header[] headers = resp.getAllHeaders();
        for (final Header header : headers)
            if (header.getName().equals("Set-Cookie")) {
                final String value = header.getValue();
                final String[] split = value.split(Pattern.quote("; "));
                for (final String s : split) {
                    if (s.contains("=")) {
                        final String[] split2 = s.split(Pattern.quote("="));
                        final String key = split2[0];
                        final String val = split2[1];
                        if (key.equals("scratchsessionsid"))
                            ssi = val;
                        else if (key.equals("scratchcsrftoken"))
                            sct = val;
                        else if (key.equals("expires"))
                            e = val;
                    }
                }
            }
        resp.close();

        return new ScratchSession(ssi, sct, e, username);
    } catch (final IOException e) {
        e.printStackTrace();
        throw new ScratchLoginException();
    }
}

From source file:org.fao.geonet.api.records.editing.InspireValidatorUtils.java

/**
 * Check service status./*w  w w .j a  v a2  s.  c o  m*/
 *
 * @param endPoint the end point
 * @param client the client (optional) (optional)
 * @return true, if successful
 */
public static boolean checkServiceStatus(String endPoint, CloseableHttpClient client) {

    boolean close = false;
    if (client == null) {
        client = HttpClients.createDefault();
        close = true;
    }
    HttpGet request = new HttpGet(endPoint + CheckStatus_URL);

    // add request header
    request.addHeader("User-Agent", USER_AGENT);
    request.addHeader("Accept", ACCEPT);
    HttpResponse response;

    try {
        response = client.execute(request);
    } catch (Exception e) {
        Log.warning(Log.SERVICE, "Error calling INSPIRE service: " + endPoint, e);
        return false;
    } finally {
        if (close) {
            try {
                client.close();
            } catch (IOException e) {
                Log.error(Log.SERVICE, "Error closing CloseableHttpClient: " + endPoint, e);
            }
        }
    }

    if (response.getStatusLine().getStatusCode() == 200) {
        return true;
    } else {
        Log.warning(Log.SERVICE, "INSPIRE service not available: " + endPoint + CheckStatus_URL);
        return false;
    }
}

From source file:utils.ImportExportUtils.java

/**
 * Registering the clientApplication/*from  w ww .  j  a va 2 s.co m*/
 * @param username user name of the client
 * @param password password of the client
 */
static String registerClient(String username, String password) throws APIExportException {

    ApiImportExportConfiguration config = ApiImportExportConfiguration.getInstance();

    String concatUsernamePassword = username + ":" + password;
    byte[] encodedBytes = Base64
            .encodeBase64(concatUsernamePassword.getBytes(Charset.forName(ImportExportConstants.CHARSET)));
    String encodedCredentials;
    try {
        encodedCredentials = new String(encodedBytes, ImportExportConstants.CHARSET);
    } catch (UnsupportedEncodingException e) {
        String error = "Error occurred while encoding the user credentials";
        log.error(error, e);
        throw new APIExportException(error, e);
    }
    //payload for registering
    JSONObject jsonObject = new JSONObject();
    jsonObject.put(ImportExportConstants.CLIENT_NAME, config.getClientName());
    jsonObject.put(ImportExportConstants.OWNER, username);
    jsonObject.put(ImportExportConstants.GRANT_TYPE, ImportExportConstants.DEFAULT_GRANT_TYPE);
    jsonObject.put(ImportExportConstants.SAAS_APP, true);

    //REST API call for registering
    CloseableHttpResponse response;
    String encodedConsumerDetails;
    CloseableHttpClient client = null;
    try {
        String url = config.getDcrUrl();
        client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate());
        HttpPost request = new HttpPost(url);
        request.setEntity(new StringEntity(jsonObject.toJSONString(), ImportExportConstants.CHARSET));
        request.setHeader(HttpHeaders.AUTHORIZATION,
                ImportExportConstants.AUTHORIZATION_KEY_SEGMENT + " " + encodedCredentials);
        request.setHeader(HttpHeaders.CONTENT_TYPE, ImportExportConstants.CONTENT_JSON);
        response = client.execute(request);

        if (response.getStatusLine().getStatusCode() == 401) {
            String errormsg = "invalid username or password entered ";
            log.error(errormsg);
            throw new APIExportException(errormsg);
        }
        String jsonString = EntityUtils.toString(response.getEntity());
        JSONObject jsonObj = (JSONObject) new JSONParser().parse(jsonString);

        //storing encoded Consumer credentials
        String consumerCredentials = jsonObj.get(ImportExportConstants.CLIENT_ID) + ":"
                + jsonObj.get(ImportExportConstants.CLIENT_SECRET);
        byte[] bytes = Base64.encodeBase64(consumerCredentials.getBytes(Charset.defaultCharset()));
        encodedConsumerDetails = new String(bytes, ImportExportConstants.CHARSET);
    } catch (ParseException e) {
        String msg = "error occurred while getting consumer key and consumer secret from the response";
        log.error(msg, e);
        throw new APIExportException(msg, e);
    } catch (IOException e) {
        String msg = "Error occurred while registering the client";
        log.error(msg, e);
        throw new APIExportException(msg, e);
    } finally {
        IOUtils.closeQuietly(client);
    }
    return encodedConsumerDetails;
}

From source file:com.vaushell.superpipes.tools.HTTPhelper.java

/**
 * Is a URI exist (HTTP response code between 200 and 299).
 *
 * @param client HTTP client.//from ww  w.  ja  v  a2  s  .  co m
 * @param uri the URI.
 * @param timeout how many ms to wait ? (could be null)
 * @return true if it exists.
 * @throws IOException
 */
public static boolean isURIvalid(final CloseableHttpClient client, final URI uri, final Duration timeout)
        throws IOException {
    if (client == null || uri == null) {
        throw new IllegalArgumentException();
    }

    HttpEntity responseEntity = null;
    try {
        // Exec request
        final HttpGet get = new HttpGet(uri);

        if (timeout != null && timeout.getMillis() > 0L) {
            get.setConfig(RequestConfig.custom().setConnectTimeout((int) timeout.getMillis())
                    .setConnectionRequestTimeout((int) timeout.getMillis())
                    .setSocketTimeout((int) timeout.getMillis()).build());
        }

        try (final CloseableHttpResponse response = client.execute(get)) {
            final StatusLine sl = response.getStatusLine();
            responseEntity = response.getEntity();

            return sl.getStatusCode() >= 200 && sl.getStatusCode() < 300;
        }
    } finally {
        if (responseEntity != null) {
            EntityUtils.consumeQuietly(responseEntity);
        }
    }
}

From source file:org.wltea.analyzer.dic.Dictionary.java

/**
 * ???/*from w w  w .  j  a v  a  2 s . com*/
 */
private static List<String> getRemoteWords(String location) {

    List<String> buffer = new ArrayList<String>();
    RequestConfig rc = RequestConfig.custom().setConnectionRequestTimeout(10 * 1000)
            .setConnectTimeout(10 * 1000).setSocketTimeout(60 * 1000).build();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response;
    BufferedReader in;
    HttpGet get = new HttpGet(location);
    get.setConfig(rc);
    try {
        response = httpclient.execute(get);
        if (response.getStatusLine().getStatusCode() == 200) {

            String charset = "UTF-8";
            // ??utf-8
            if (response.getEntity().getContentType().getValue().contains("charset=")) {
                String contentType = response.getEntity().getContentType().getValue();
                charset = contentType.substring(contentType.lastIndexOf("=") + 1);
            }
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), charset));
            String line;
            while ((line = in.readLine()) != null) {
                buffer.add(line);
            }
            in.close();
            response.close();
            return buffer;
        }
        response.close();
    } catch (ClientProtocolException e) {
        logger.error("getRemoteWords {} error", e, location);
    } catch (IllegalStateException e) {
        logger.error("getRemoteWords {} error", e, location);
    } catch (IOException e) {
        logger.error("getRemoteWords {} error", e, location);
    }
    return buffer;
}

From source file:org.eclipselabs.garbagecat.Main.java

/**
 * @return version string.// www  . java2  s .  co  m
 */
private static String getLatestVersion() {
    String url = "https://github.com/mgm3746/garbagecat/releases/latest";
    String name = null;
    try {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        httpClient = HttpClients.custom()
                .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
                .build();
        HttpGet request = new HttpGet(url);
        request.addHeader("Accept", "application/json");
        request.addHeader("content-type", "application/json");
        HttpResponse result = httpClient.execute(request);
        String json = EntityUtils.toString(result.getEntity(), "UTF-8");
        JSONObject jsonObj = new JSONObject(json);
        name = jsonObj.getString("tag_name");
    }

    catch (Exception ex) {
        name = "Unable to retrieve";
        ex.printStackTrace();
    }
    return name;
}

From source file:com.glaf.core.util.http.HttpClientUtils.java

/**
 * ??POST//w  ww .  j  a  va 2  s .  co  m
 * 
 * @param url
 *            ??
 * @param encoding
 *            
 * @param dataMap
 *            ?
 * 
 * @return
 */
public static String doPost(String url, String encoding, Map<String, String> dataMap) {
    StringBuffer buffer = new StringBuffer();
    HttpPost post = null;
    InputStreamReader is = null;
    BufferedReader reader = null;
    BasicCookieStore cookieStore = new BasicCookieStore();
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.setDefaultCookieStore(cookieStore).build();
    try {
        post = new HttpPost(url);
        if (dataMap != null && !dataMap.isEmpty()) {
            List<org.apache.http.NameValuePair> nameValues = new ArrayList<org.apache.http.NameValuePair>();
            for (Map.Entry<String, String> entry : dataMap.entrySet()) {
                String name = entry.getKey().toString();
                String value = entry.getValue();
                nameValues.add(new BasicNameValuePair(name, value));
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValues, encoding);
            post.setEntity(entity);
        }
        HttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
        is = new InputStreamReader(entity.getContent(), encoding);
        reader = new BufferedReader(is);
        String tmp = reader.readLine();
        while (tmp != null) {
            buffer.append(tmp);
            tmp = reader.readLine();
        }

    } catch (IOException ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(reader);
        IOUtils.closeStream(is);
        if (post != null) {
            post.releaseConnection();
        }
        try {
            client.close();
        } catch (IOException ex) {
        }
    }
    return buffer.toString();
}

From source file:org.fao.geonet.api.records.editing.InspireValidatorUtils.java

/**
 * Gets the tests.//from ww  w.j ava2 s.  c om
 *
 * @param endPoint the end point
 * @param client the client (optional)
 * @return the tests
 */
private static List<String> getTests(String endPoint, CloseableHttpClient client) {

    boolean close = false;
    if (client == null) {
        client = HttpClients.createDefault();
        close = true;
    }

    try {

        HttpGet request = new HttpGet(endPoint + ExecutableTestSuites_URL);

        request.addHeader("User-Agent", USER_AGENT);
        request.addHeader("Accept", ACCEPT);
        HttpResponse response;

        response = client.execute(request);

        if (response.getStatusLine().getStatusCode() == 200) {

            List<String> testList = new ArrayList<>();

            ResponseHandler<String> handler = new BasicResponseHandler();
            String body = handler.handleResponse(response);

            JSONObject jsonRoot = new JSONObject(body);

            JSONObject etfItemCollection = jsonRoot.getJSONObject("EtfItemCollection");
            JSONObject executableTestSuites = etfItemCollection.getJSONObject("executableTestSuites");
            JSONArray executableTestSuiteArray = executableTestSuites.getJSONArray("ExecutableTestSuite");

            for (int i = 0; i < executableTestSuiteArray.length(); i++) {
                JSONObject test = executableTestSuiteArray.getJSONObject(i);

                boolean ok = false;

                for (String testToRun : TESTS_TO_RUN) {
                    ok = ok || testToRun.equals(test.getString("label"));
                }

                if (ok) {
                    testList.add(test.getString("id"));
                }
            }

            return testList;
        } else {
            Log.warning(Log.SERVICE, "WARNING: INSPIRE service HTTP response: "
                    + response.getStatusLine().getStatusCode() + " for " + ExecutableTestSuites_URL);
            return null;
        }
    } catch (Exception e) {
        Log.error(Log.SERVICE, "Exception in INSPIRE service: " + endPoint, e);
        return null;
    } finally {
        if (close) {
            try {
                client.close();
            } catch (IOException e) {
                Log.error(Log.SERVICE, "Error closing CloseableHttpClient: " + endPoint, e);
            }
        }
    }
}

From source file:com.glaf.core.util.http.HttpClientUtils.java

/**
 * ??GET//from  w w  w  .ja  v a  2 s .  c o  m
 * 
 * @param url
 *            ??
 * @param encoding
 *            
 * @param dataMap
 *            ?
 * 
 * @return
 */
public static String doGet(String url, String encoding, Map<String, String> dataMap) {
    StringBuffer buffer = new StringBuffer();
    HttpGet httpGet = null;
    InputStreamReader is = null;
    BufferedReader reader = null;
    BasicCookieStore cookieStore = new BasicCookieStore();
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.setDefaultCookieStore(cookieStore).build();
    try {
        if (dataMap != null && !dataMap.isEmpty()) {
            StringBuffer sb = new StringBuffer();
            for (Map.Entry<String, String> entry : dataMap.entrySet()) {
                String name = entry.getKey().toString();
                String value = entry.getValue();
                sb.append("&").append(name).append("=").append(value);
            }
            if (StringUtils.contains(url, "?")) {
                url = url + sb.toString();
            } else {
                url = url + "?xxxx=1" + sb.toString();
            }
        }
        httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        is = new InputStreamReader(entity.getContent(), encoding);
        reader = new BufferedReader(is);
        String tmp = reader.readLine();
        while (tmp != null) {
            buffer.append(tmp);
            tmp = reader.readLine();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(reader);
        IOUtils.closeStream(is);
        if (httpGet != null) {
            httpGet.releaseConnection();
        }
        try {
            client.close();
        } catch (IOException ex) {
        }
    }
    return buffer.toString();
}

From source file:com.rtl.http.Upload.java

private static String send(String message, InputStream fileIn, String url) throws Exception {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000)
            .build();// 
    post.setConfig(requestConfig);/*from ww  w .j  a va2 s  .  com*/
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setCharset(Charset.forName("UTF-8"));// ?
    ContentType contentType = ContentType.create("text/html", "UTF-8");
    builder.addPart("reqParam", new StringBody(message, contentType));
    builder.addPart("version", new StringBody("1.0", contentType));
    builder.addPart("dataFile", new InputStreamBody(fileIn, "file"));
    post.setEntity(builder.build());
    CloseableHttpResponse response = client.execute(post);
    InputStream inputStream = null;
    String responseStr = "", sCurrentLine = "";
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        inputStream = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((sCurrentLine = reader.readLine()) != null) {
            responseStr = responseStr + sCurrentLine;
        }
        return responseStr;
    }
    return null;
}