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:org.wuspba.ctams.ui.server.ServerUtils.java

public static String post(URI uri, String xml) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(uri);
    StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    String ret;//from w w  w  .  java  2  s  .  c om

    httpPost.setEntity(xmlEntity);

    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        HttpEntity entity = response.getEntity();

        ret = convertEntity(entity);

        EntityUtils.consume(entity);
    }

    return ret;
}

From source file:net.yacy.grid.http.ClientConnection.java

/**
 * get a redirect for an url: this method shall be called if it is expected that a url
 * is redirected to another url. This method then discovers the redirect.
 * @param urlstring//from   w w w.j  a  va 2 s .  c om
 * @param useAuthentication
 * @return the redirect url for the given urlstring
 * @throws IOException if the url is not redirected
 */
public static String getRedirect(String urlstring) throws IOException {
    HttpGet get = new HttpGet(urlstring);
    get.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build());
    get.setHeader("User-Agent",
            ClientIdentification.getAgent(ClientIdentification.yacyInternetCrawlerAgentName).userAgent);
    CloseableHttpClient httpClient = getClosableHttpClient();
    HttpResponse httpResponse = httpClient.execute(get);
    HttpEntity httpEntity = httpResponse.getEntity();
    if (httpEntity != null) {
        if (httpResponse.getStatusLine().getStatusCode() == 301) {
            for (Header header : httpResponse.getAllHeaders()) {
                if (header.getName().equalsIgnoreCase("location")) {
                    EntityUtils.consumeQuietly(httpEntity);
                    return header.getValue();
                }
            }
            EntityUtils.consumeQuietly(httpEntity);
            throw new IOException("redirect for  " + urlstring + ": no location attribute found");
        } else {
            EntityUtils.consumeQuietly(httpEntity);
            throw new IOException(
                    "no redirect for  " + urlstring + " fail: " + httpResponse.getStatusLine().getStatusCode()
                            + ": " + httpResponse.getStatusLine().getReasonPhrase());
        }
    } else {
        throw new IOException("client connection to " + urlstring + " fail: no connection");
    }
}

From source file:org.sead.repositories.reference.util.SEADGoogleLogin.java

static void getTokensFromCode() {
    access_token = null;/*  w  w w .  j  ava2s  . c om*/
    expires_in = -1;
    token_start_time = -1;
    refresh_token = null;
    new File("refresh.txt").delete();

    if (gProps == null) {
        initGProps();
    }
    // Query for token now that user has gone through browser part
    // of
    // flow
    HttpPost tokenRequest = new HttpPost(gProps.token_uri);

    MultipartEntityBuilder tokenRequestParams = MultipartEntityBuilder.create();
    tokenRequestParams.addTextBody("client_id", gProps.client_id);
    tokenRequestParams.addTextBody("client_secret", gProps.client_secret);
    tokenRequestParams.addTextBody("code", device_code);
    tokenRequestParams.addTextBody("grant_type", "http://oauth.net/grant_type/device/1.0");

    HttpEntity reqEntity = tokenRequestParams.build();

    tokenRequest.setEntity(reqEntity);
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(tokenRequest);

        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                String responseJSON = EntityUtils.toString(resEntity);
                ObjectNode root = (ObjectNode) new ObjectMapper().readTree(responseJSON);
                access_token = root.get("access_token").asText();
                refresh_token = root.get("refresh_token").asText();
                token_start_time = System.currentTimeMillis() / 1000;
                expires_in = root.get("expires_in").asInt();
            }
        } else {
            log.error("Error response from Google: " + response.getStatusLine().getReasonPhrase());
        }
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            httpclient.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

From source file:com.aws.sampleImage.url.LambdaFunctionImageURLCrawlerHandler.java

private static String callFlickrAPIForEachKeyword(String query, String synsetCode)
        throws IOException, JSONException {
    String apiKey = "ad4f88ecfd53b17f93178e19703fe00d";
    String apiSecret = "96cab0e9f89468d6";

    int totalPages = 4;

    int total = 500;
    int perPage = 500;

    int counter = 0;//For monitoring purposes only

    int currentCount = 0;

    for (int i = 1; i <= totalPages && currentCount <= total; i++, currentCount = currentCount + perPage) {

        StringBuffer sb = new StringBuffer(512);
        sb.append("https://api.flickr.com/services/rest/?method=flickr.photos.search&text=").append(query)
                .append("&extras=url_c,url_m,url_n,license,owner_name&per_page=500&page=").append(i)
                .append("&format=json&api_key=").append(apiKey).append("&api_secret=").append(apiSecret)
                .append("&license=4,5,6,7,8");

        String url = sb.toString();

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

        //System.out.println("GET Response Status:: " + httpResponse.getStatusLine().getStatusCode());

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(httpResponse.getEntity().getContent()));

        String inputLine;//from ww w.  j  a v a  2s.com
        StringBuffer response = new StringBuffer();

        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();

        String responseString = response.toString();

        responseString = responseString.replace("jsonFlickrApi(", "");

        int length = responseString.length();

        responseString = responseString.substring(0, length - 1);

        // print result
        httpClient.close();

        JSONObject json = null;
        try {
            json = new JSONObject(responseString);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //System.out.println("Converted JSON String " + json);

        JSONObject photosObj = json.has("photos") ? json.getJSONObject("photos") : null;
        total = photosObj.has("total") ? (Integer.parseInt(photosObj.getString("total"))) : 0;
        perPage = photosObj.has("perpage") ? (Integer.parseInt(photosObj.getString("perpage"))) : 0;

        //System.out.println(" perPage --> " + perPage + " total --> " + total);

        JSONArray photoArr = photosObj.getJSONArray("photo");
        //System.out.println("Length of Array --> " + photoArr.length());
        String scrapedImageURL = "";

        for (int itr = 0; itr < photoArr.length(); itr++) {
            JSONObject tempObject = photoArr.getJSONObject(itr);
            scrapedImageURL = tempObject.has("url_c") ? tempObject.getString("url_c")
                    : tempObject.has("url_m") ? tempObject.getString("url_m")
                            : tempObject.has("url_n") ? tempObject.getString("url_n") : "";

            //System.out.println("Scraped Image URL, need to insert this to Amazon DYnamo DB --> " + scrapedImageURL);

            counter++;

            insertScrapedImageURLsInDynamoDB(scrapedImageURL, synsetCode, query);
        }

    }

    System.out.println("C O U N T E R -> " + counter);
    return null;
}

From source file:org.smartloli.kafka.eagle.common.util.HttpClientUtils.java

/**
 * Send request by post method.//from   w ww. jav a 2  s.c o  m
 * 
 * @param uri:
 *            http://ip:port/demo
 * @param parames:
 *            new BasicNameValuePair("code", "200")
 * 
 *            new BasicNameValuePair("name", "smartloli")
 */
public static String doPostForm(String uri, List<BasicNameValuePair> parames) {
    String result = "";
    try {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(new UrlEncodedFormEntity(parames, "UTF-8"));
            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } finally {
            if (response != null) {
                response.close();
            }
            if (client != null) {
                client.close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LOG.error("Do post form request has error, msg is " + e.getMessage());
    }
    return result;
}

From source file:com.weitaomi.systemconfig.wechat.ClientCustomSSL.java

public static String connectKeyStore(String url, String xml, String path, int flag) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    File file = LoadFileFactory.getFile(path);
    char[] arr = null;
    if (flag == 0) {
        arr = WechatConfig.MCHID.toCharArray();
    }/*from   w  w  w .  ja va  2s  . co  m*/
    if (flag == 1) {
        arr = WechatConfig.MCHID_OFFICIAL.toCharArray();
    }
    FileInputStream instream = new FileInputStream(file);
    try {
        keyStore.load(instream, arr);
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, arr).build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

    StringEntity entityRequest = new StringEntity(xml, "utf-8");
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(entityRequest);
    //        httpPost.setHeader("Content-Type", "application/json");//; charset=utf-8
    HttpResponse response = httpclient.execute(httpPost);

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new RuntimeException("");
    }
    HttpEntity resEntity = response.getEntity();
    InputStream inputStream = resEntity.getContent();
    return HttpRequestUtils.readInstream(inputStream, "UTF-8");
}

From source file:org.keycloak.helper.TestsHelper.java

public static boolean testGetWithAuth(String endpoint, String token) throws IOException {
    CloseableHttpClient client = HttpClientBuilder.create().build();

    try {/*from   www.  java2s  .c  o m*/
        HttpGet get = new HttpGet(baseUrl + endpoint);
        get.addHeader("Authorization", "Bearer " + token);

        HttpResponse response = client.execute(get);
        if (response.getStatusLine().getStatusCode() != 200) {
            return false;
        }
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();
        try {
            return true;
        } finally {
            is.close();
        }

    } finally {
        client.close();
    }
}

From source file:adalid.util.google.Translator.java

private static String translate(String arg, URIBuilder builder, CloseableHttpClient client)
        throws IOException, URISyntaxException {
    builder.clearParameters();//w  w w .  j a  va2 s.com
    builder.setParameter("langpair", "en|es");
    builder.setParameter("text", arg);
    URI uri = builder.build();
    HttpGet get = new HttpGet(uri);
    HttpUriRequest request = (HttpUriRequest) get;
    try (CloseableHttpResponse response = client.execute(request)) {
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getReasonPhrase().equals("OK")) {
            logger.info(statusLine.toString());
        } else {
            throw new RuntimeException(statusLine.toString());
        }
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            logger.info(entity.getContentType());
            return translate(entity);
        }
    } catch (ClientProtocolException ex) {
        logger.fatal(uri, ex);
    }
    return null;
}

From source file:com.fishcart.delivery.util.HttpClient.java

public static String postWhatsapp(String url, String nos, String message) {
    try {//from  www  . j  a  va2s  .c o  m
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("nos", nos));
        urlParameters.add(new BasicNameValuePair("message", message));
        post.setEntity(new UrlEncodedFormEntity(urlParameters));
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuilder result = new StringBuilder();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        return result.toString();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }

}

From source file:de.intevation.irix.PrintClient.java

/** Obtains a Report from mapfish-print service.
 *
 * @param printUrl The url to send the request to.
 * @param json The json spec for the print request.
 * @param timeout the timeout for the httpconnection.
 *
 * @return byte[] with the report.// w w w  .  j a va  2s .  c o m
 *
 * @throws IOException if communication with print service failed.
 * @throws PrintException if the print job failed.
 */
public static byte[] getReport(String printUrl, String json, int timeout) throws IOException, PrintException {

    RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).build();

    CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();

    HttpEntity entity = new StringEntity(json,
            ContentType.create("application/json", Charset.forName("UTF-8")));

    HttpPost post = new HttpPost(printUrl);
    post.setEntity(entity);
    CloseableHttpResponse resp = client.execute(post);

    StatusLine status = resp.getStatusLine();

    byte[] retval = null;
    try {
        HttpEntity respEnt = resp.getEntity();
        InputStream in = respEnt.getContent();
        if (in != null) {
            try {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buf = new byte[BYTE_ARRAY_SIZE];
                int r;
                while ((r = in.read(buf)) >= 0) {
                    out.write(buf, 0, r);
                }
                retval = out.toByteArray();
            } finally {
                in.close();
                EntityUtils.consume(respEnt);
            }
        }
    } finally {
        resp.close();
    }

    if (status.getStatusCode() < HttpURLConnection.HTTP_OK
            || status.getStatusCode() >= HttpURLConnection.HTTP_MULT_CHOICE) {
        if (retval != null) {
            throw new PrintException(new String(retval));
        } else {
            throw new PrintException("Communication with print service '" + printUrl + "' failed."
                    + "\nNo response from print service.");
        }
    }
    return retval;
}