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:utils.APIImporter.java

private static void addAPIImage(String folderPath, String accessToken, String uuid) {
    File apiFolder = new File(folderPath);
    File[] fileArray = apiFolder.listFiles();
    if (fileArray != null) {
        for (File file : fileArray) {
            String fileName = file.getName();
            String imageName = fileName.substring(0, fileName.indexOf("."));
            if (imageName.equalsIgnoreCase(ImportExportConstants.IMG_NAME)) {
                File imageFile = new File(folderPath + ImportExportConstants.ZIP_FILE_SEPARATOR + fileName);
                MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
                multipartEntityBuilder.addBinaryBody(ImportExportConstants.MULTIPART_FILE, imageFile);
                HttpEntity entity = multipartEntityBuilder.build();
                String url = config.getPublisherUrl() + "apis/" + uuid + "/thumbnail";
                CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate());
                HttpPost request = new HttpPost(url);
                request.setHeader(HttpHeaders.AUTHORIZATION,
                        ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + accessToken);
                request.setEntity(entity);
                try {
                    client.execute(request);
                } catch (IOException e) {
                    errorMsg = "Error occurred while publishing the API thumbnail";
                    log.error(errorMsg, e);
                }//from   ww  w .  j ava  2  s. c  o m
                break;
            }
        }
    }
}

From source file:emea.summit.architects.HackathlonAPIResource.java

private static String getRequest(String url, String contentType) throws Exception {
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.build();
    HttpUriRequest get = new HttpGet(url);
    get.setHeader("Content-Type", contentType);

    HttpResponse response = client.execute(get);
    StatusLine status = response.getStatusLine();
    String content = EntityUtils.toString(response.getEntity());
    //JSONObject json = new JSONObject(content);

    return content;
}

From source file:emea.summit.architects.HackathlonAPIResource.java

private static String putRequest(String url, String contentType) throws Exception {
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.build();
    HttpUriRequest put = new HttpPut(url);
    put.setHeader("Content-Type", contentType);

    HttpResponse response = client.execute(put);
    StatusLine status = response.getStatusLine();
    String content = EntityUtils.toString(response.getEntity());
    //JSONObject json = new JSONObject(content);

    return content;
}

From source file:org.wso2.mdm.qsg.utils.HTTPInvoker.java

public static HTTPResponse sendHTTPPostWithURLParams(String url, List<NameValuePair> params,
        HashMap<String, String> headers) {
    HttpPost post = null;/*  ww  w .  j a  va2 s  . com*/
    HttpResponse response = null;
    CloseableHttpClient httpclient = null;
    HTTPResponse httpResponse = new HTTPResponse();
    try {
        httpclient = (CloseableHttpClient) createHttpClient();
        post = new HttpPost(url);
        post.setEntity(new UrlEncodedFormEntity(params));
        for (String key : headers.keySet()) {
            post.setHeader(key, headers.get(key));
        }
        response = httpclient.execute(post);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    BufferedReader rd = null;
    try {
        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    } catch (IOException e) {
        e.printStackTrace();
    }

    StringBuffer result = new StringBuffer();
    String line = "";
    try {
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    httpResponse.setResponseCode(response.getStatusLine().getStatusCode());
    httpResponse.setResponse(result.toString());
    return httpResponse;
}

From source file:com.ibm.watson.developer_cloud.professor_languo.pipeline.RnrMergerAndRanker.java

/**
 * Deletes the specified ranker/*from  w ww. j a v  a2 s  .co  m*/
 * 
 * @param ranker_id ofthe ranker to be deleted
 * @throws ClientProtocolException
 * @throws IOException
 * @throws JSONException
 */
public static void deleteRanker(CloseableHttpClient client, String ranker_id)
        throws ClientProtocolException, IOException {

    JSONObject res;

    try {
        HttpDelete httpdelete = new HttpDelete(ranker_url + "/" + ranker_id);
        httpdelete.setHeader("Content-Type", "application/json");
        CloseableHttpResponse response = client.execute(httpdelete);

        try {

            String result = EntityUtils.toString(response.getEntity());
            res = (JSONObject) JSON.parse(result);
            if (res.isEmpty()) {
                logger.info(MessageFormat.format(Messages.getString("RetrieveAndRank.RANKER_DELETE"), //$NON-NLS-1$
                        ranker_id));
            } else {
                logger.info(MessageFormat.format(Messages.getString("RetrieveAndRank.RANKER_DELETE_FAIL"), //$NON-NLS-1$
                        ranker_id));
            }
        } catch (NullPointerException | JSONException e) {
            logger.error(e.getMessage());
        }

        finally {
            response.close();
        }
    }

    finally {
        client.close();
    }
}

From source file:org.wso2.mdm.qsg.utils.HTTPInvoker.java

public static HTTPResponse sendHTTPPostWithOAuthSecurity(String url, HttpEntity entity,
        HashMap<String, String> headers) {
    HttpPost post = null;/*from w  ww.j ava2s .c o m*/
    HttpResponse response = null;
    HTTPResponse httpResponse = new HTTPResponse();
    CloseableHttpClient httpclient = null;
    try {
        httpclient = (CloseableHttpClient) createHttpClient();
        post = new HttpPost(url);
        post.setEntity(entity);
        for (String key : headers.keySet()) {
            post.setHeader(key, headers.get(key));
        }
        post.setHeader(Constants.Header.AUTH, OAUTH_BEARER + oAuthToken);
        response = httpclient.execute(post);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    BufferedReader rd = null;
    try {
        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    } catch (IOException e) {
        e.printStackTrace();
    }

    StringBuffer result = new StringBuffer();
    String line = "";
    try {
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    httpResponse.setResponseCode(response.getStatusLine().getStatusCode());
    httpResponse.setResponse(result.toString());
    try {
        httpclient.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return httpResponse;
}

From source file:org.wuspba.ctams.ws.ITPersonController.java

protected static void delete() throws Exception {
    List<String> ids = new ArrayList<>();

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpGet httpGet = new HttpGet(uri);

    try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
        assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING);

        HttpEntity entity = response.getEntity();

        CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity);

        for (Person p : doc.getPeople()) {
            ids.add(p.getId());//  w  w w.ja v  a 2 s. c  o  m
        }

        EntityUtils.consume(entity);
    }

    for (String id : ids) {
        httpclient = HttpClients.createDefault();

        uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
                .setParameter("id", id).build();

        HttpDelete httpDelete = new HttpDelete(uri);

        CloseableHttpResponse response = null;

        try {
            response = httpclient.execute(httpDelete);

            assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

            HttpEntity responseEntity = response.getEntity();

            EntityUtils.consume(responseEntity);
        } catch (UnsupportedEncodingException ex) {
            LOG.error("Unsupported coding", ex);
        } catch (IOException ioex) {
            LOG.error("IOException", ioex);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ex) {
                    LOG.error("Could not close response", ex);
                }
            }
        }
    }
}

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

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

    if (gProps == null) {
        initGProps();
    }

    // Contact google for a user code
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {

        String codeUri = gProps.auth_uri.substring(0, gProps.auth_uri.length() - 4) + "device/code";

        HttpPost codeRequest = new HttpPost(codeUri);

        MultipartEntityBuilder meb = MultipartEntityBuilder.create();
        meb.addTextBody("client_id", gProps.client_id);
        meb.addTextBody("scope", "email profile");
        HttpEntity reqEntity = meb.build();

        codeRequest.setEntity(reqEntity);
        CloseableHttpResponse response = httpclient.execute(codeRequest);
        try {

            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    String responseJSON = EntityUtils.toString(resEntity);
                    ObjectNode root = (ObjectNode) new ObjectMapper().readTree(responseJSON);
                    device_code = root.get("device_code").asText();
                    user_code = root.get("user_code").asText();
                    verification_url = root.get("verification_url").asText();
                    expires_in = root.get("expires_in").asInt();
                }
            } else {
                log.error("Error response from Google: " + response.getStatusLine().getReasonPhrase());
            }
        } finally {
            response.close();
            httpclient.close();
        }
    } catch (IOException e) {
        log.error("Error reading sead-google.json or making http requests for code.");
        log.error(e.getMessage());
    }
}

From source file:org.wso2.mdm.qsg.utils.HTTPInvoker.java

public static HTTPResponse sendHTTPPost(String url, String payload, HashMap<String, String> headers) {
    HttpPost post = null;// w  w  w  . j  ava  2s.  c o m
    HttpResponse response = null;
    HTTPResponse httpResponse = new HTTPResponse();
    CloseableHttpClient httpclient = null;
    try {
        httpclient = (CloseableHttpClient) createHttpClient();
        StringEntity requestEntity = new StringEntity(payload, Constants.UTF_8);
        post = new HttpPost(url);
        post.setEntity(requestEntity);
        for (String key : headers.keySet()) {
            post.setHeader(key, headers.get(key));
        }
        response = httpclient.execute(post);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    BufferedReader rd = null;
    try {
        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    } catch (IOException e) {
        e.printStackTrace();
    }

    StringBuffer result = new StringBuffer();
    String line = "";
    try {
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    httpResponse.setResponseCode(response.getStatusLine().getStatusCode());
    httpResponse.setResponse(result.toString());
    try {
        httpclient.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return httpResponse;
}

From source file:eu.diacron.crawlservice.app.Util.java

public static void getAllCrawls() {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(Configuration.REMOTE_CRAWLER_USERNAME,
                    Configuration.REMOTE_CRAWLER_PASS));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {//  w w  w . jav  a2  s .  com
        //HttpGet httpget = new HttpGet("http://diachron.hanzoarchives.com/crawl");
        HttpGet httpget = new HttpGet(Configuration.REMOTE_CRAWLER_URL_CRAWL);

        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println("----------------------------------------");

            System.out.println(response.getEntity().getContent());

            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
            in.close();
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } catch (IOException ex) {
        Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            httpclient.close();
        } catch (IOException ex) {
            Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}