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.ws.ITBandController.java

public static void delete() throws Exception {
    String id;// ww w . ja  va2s .  c o m

    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);

        id = doc.getBands().get(0).getId();

        EntityUtils.consume(entity);
    }

    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:com.vmware.identity.openidconnect.client.OIDCClientUtils.java

static HttpResponse sendSecureRequest(HttpRequest httpRequest, SSLContext sslContext)
        throws OIDCClientException, SSLConnectionException {
    Validate.notNull(httpRequest, "httpRequest");
    Validate.notNull(sslContext, "sslContext");

    RequestConfig config = RequestConfig.custom().setConnectTimeout(HTTP_CLIENT_TIMEOUT_MILLISECS)
            .setConnectionRequestTimeout(HTTP_CLIENT_TIMEOUT_MILLISECS)
            .setSocketTimeout(HTTP_CLIENT_TIMEOUT_MILLISECS).build();

    CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setDefaultRequestConfig(config)
            .build();/* www. j  a v  a 2 s .  co  m*/

    CloseableHttpResponse closeableHttpResponse = null;

    try {
        HttpRequestBase httpTask = httpRequest.toHttpTask();
        closeableHttpResponse = client.execute(httpTask);

        int statusCodeInt = closeableHttpResponse.getStatusLine().getStatusCode();
        StatusCode statusCode;
        try {
            statusCode = StatusCode.parse(statusCodeInt);
        } catch (ParseException e) {
            throw new OIDCClientException("failed to parse status code", e);
        }
        JSONObject jsonContent = null;
        HttpEntity httpEntity = closeableHttpResponse.getEntity();
        if (httpEntity != null) {
            ContentType contentType;
            try {
                contentType = ContentType.get(httpEntity);
            } catch (UnsupportedCharsetException | org.apache.http.ParseException e) {
                throw new OIDCClientException("Error in setting content type in HTTP response.");
            }
            if (!StandardCharsets.UTF_8.equals(contentType.getCharset())) {
                throw new OIDCClientException("unsupported charset: " + contentType.getCharset());
            }
            if (!ContentType.APPLICATION_JSON.getMimeType().equalsIgnoreCase(contentType.getMimeType())) {
                throw new OIDCClientException("unsupported mime type: " + contentType.getMimeType());
            }
            String content = EntityUtils.toString(httpEntity);
            try {
                jsonContent = JSONUtils.parseJSONObject(content);
            } catch (ParseException e) {
                throw new OIDCClientException("failed to parse json response", e);
            }
        }

        closeableHttpResponse.close();
        client.close();

        return HttpResponse.createJsonResponse(statusCode, jsonContent);
    } catch (IOException e) {
        throw new OIDCClientException("IOException caught in HTTP communication:" + e.getMessage(), e);
    }
}

From source file:com.bacic5i5j.framework.toolbox.web.WebUtils.java

/**
 * ??/* w w  w .j  a  v a  2 s .  c  o  m*/
 *
 * @param params
 * @param url
 * @return
 */
public static String post(Map<String, String> params, String url) {
    String result = "";

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);

    List<NameValuePair> nvps = generateURLParams(params);
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage() + " : " + e.getCause());
    }

    CloseableHttpResponse response = null;

    try {
        response = httpClient.execute(httpPost);
    } catch (IOException e) {
        log.error(e.getMessage() + " : " + e.getCause());
    }

    if (response != null) {
        StatusLine statusLine = response.getStatusLine();
        log.info("??: " + statusLine.getStatusCode());
        if (statusLine.getStatusCode() == 200 || statusLine.getStatusCode() == 302) {
            try {
                InputStream is = response.getEntity().getContent();
                int count = is.available();
                byte[] buffer = new byte[count];
                is.read(buffer);
                result = new String(buffer);
            } catch (IOException e) {
                log.error("???: " + e.getMessage());
            }
        }
    }

    return result;
}

From source file:org.wso2.security.tools.zap.ext.zapwso2jiraplugin.JiraRestClient.java

public static void invokePutMethodWithFile(String auth, String url, String path) {

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost(url);
    httppost.setHeader(IssueCreatorConstants.ATLASSIAN_TOKEN, "nocheck");
    httppost.setHeader(IssueCreatorConstants.ATLASSIAN_AUTHORIZATION, "Basic " + auth);

    File fileToUpload = new File(path);
    FileBody fileBody = new FileBody(fileToUpload);

    HttpEntity entity = MultipartEntityBuilder.create().addPart("file", fileBody).build();

    httppost.setEntity(entity);/*  ww  w .  ja  va 2s  . c om*/
    CloseableHttpResponse response = null;

    try {
        response = httpclient.execute(httppost);
    } catch (Exception e) {
        log.error("File upload failed when involing the update method with file ");
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            log.error("Exception occured when closing the connection");
        }
    }
}

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

private static void add() throws Exception {
    ITVenueController.add();//  w  w w  .  j a v  a2s .c o  m
    ITJudgeController.add();
    ITBandController.add();
    ITBandContestController.add();

    CTAMSDocument doc = new CTAMSDocument();
    doc.getVenues().add(TestFixture.INSTANCE.venue);
    doc.getJudges().add(TestFixture.INSTANCE.judgeAndy);
    doc.getJudges().add(TestFixture.INSTANCE.judgeJamie);
    doc.getJudges().add(TestFixture.INSTANCE.judgeBob);
    doc.getJudges().add(TestFixture.INSTANCE.judgeEoin);
    doc.getBandContests().add(TestFixture.INSTANCE.bandContest);
    doc.getBands().add(TestFixture.INSTANCE.skye);
    doc.getBandContestEntry().add(TestFixture.INSTANCE.bandContestEntry);

    String xml = XMLUtils.marshal(doc);

    CloseableHttpClient httpclient = HttpClients.createDefault();

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

    HttpPost httpPost = new HttpPost(uri);

    StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    CloseableHttpResponse response = null;

    try {
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

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

        HttpEntity responseEntity = response.getEntity();

        doc = IntegrationTestUtils.convertEntity(responseEntity);

        TestFixture.INSTANCE.bandContestEntry.setId(doc.getBandContestEntry().get(0).getId());

        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.wuspba.ctams.ws.ITSoloContestEntryController.java

private static void add() throws Exception {
    ITVenueController.add();//w  ww  .ja va 2 s.c  o m
    ITJudgeController.add();
    ITPersonController.add();
    ITSoloContestController.add();

    CTAMSDocument doc = new CTAMSDocument();
    doc.getVenues().add(TestFixture.INSTANCE.venue);
    doc.getJudges().add(TestFixture.INSTANCE.judgeAndy);
    doc.getJudges().add(TestFixture.INSTANCE.judgeJamie);
    doc.getJudges().add(TestFixture.INSTANCE.judgeBob);
    doc.getJudges().add(TestFixture.INSTANCE.judgeEoin);
    doc.getSoloContests().add(TestFixture.INSTANCE.soloContest);
    doc.getPeople().add(TestFixture.INSTANCE.elaine);
    doc.getSoloContestEntry().add(TestFixture.INSTANCE.soloContestEntry);

    String xml = XMLUtils.marshal(doc);

    CloseableHttpClient httpclient = HttpClients.createDefault();

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

    HttpPost httpPost = new HttpPost(uri);

    StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    CloseableHttpResponse response = null;

    try {
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

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

        HttpEntity responseEntity = response.getEntity();

        doc = IntegrationTestUtils.convertEntity(responseEntity);

        TestFixture.INSTANCE.soloContestEntry.setId(doc.getSoloContestEntry().get(0).getId());

        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:com.ibm.watson.movieapp.dialog.rest.UtilityFunctions.java

/**
 * Makes HTTP PUT request/*w w  w . ja va  2  s  . c  o  m*/
 * <p>
 * This makes HTTP PUT requests to the url provided.</p>
 * 
 * @param httpClient the http client used to make the request
 * @param url the url for the request
 * @param requestJson the JSON object containing the parameters for the PUT request
 * @return the JSON object response
 * @throws ClientProtocolException if it is unable to execute the call
 * @throws IOException if it is unable to execute the call
 * @throws IllegalStateException if the input stream could not be parsed correctly
 * @throws HttpException if the HTTP call responded with a status code other than 200 or 201
 */
public static JsonObject httpPut(CloseableHttpClient httpClient, String url, JsonObject requestJson)
        throws ClientProtocolException, IOException, IllegalStateException, HttpException {
    HttpPut httpPut = new HttpPut(url);
    httpPut.addHeader("Content-Type", "application/json"); //$NON-NLS-1$ //$NON-NLS-2$
    httpPut.addHeader("Accept", "application/json"); //$NON-NLS-1$ //$NON-NLS-2$
    String inp = requestJson.toString();
    StringEntity input = new StringEntity(inp, ContentType.APPLICATION_JSON);
    httpPut.setEntity(input);
    try (CloseableHttpResponse response = httpClient.execute(httpPut)) {
        return UtilityFunctions.parseHTTPResponse(response, url);
    } catch (ClientProtocolException e) {
        throw e;
    }
}

From source file:com.webarch.common.net.http.HttpService.java

/**
 * /*from   w w  w.  j av a2 s .  c o  m*/
 * @param url ?
 * @param localPath ?
 * @param fileName ??
 * @return null/???
 */
public static String downloadFile(String url, String localPath, String fileName) {
    int bufferSize = 1024 * 10;
    String file = null;
    if (!localPath.endsWith(File.separator)) {
        localPath += File.separator;
    }
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    InputStream inputStream = null;
    FileOutputStream outputStream = null;
    try {
        HttpGet httpGet = new HttpGet(url);
        response = httpclient.execute(httpGet);
        String fileType = "dat";
        Header header = response.getLastHeader("Content-Type");
        if (header != null) {
            String headerValue = header.getValue();
            fileType = headerValue.substring(headerValue.indexOf("/") + 1, headerValue.length());
        }
        HttpEntity entity = response.getEntity();
        long length = entity.getContentLength();
        if (length <= 0) {
            logger.warn("???");
            return file;
        }
        inputStream = entity.getContent();
        file = fileName + "." + fileType;
        File outFile = new File(localPath);
        if (!outFile.exists()) {
            outFile.mkdirs();
        }
        localPath += file;
        outFile = new File(localPath);
        if (!outFile.exists()) {
            outFile.createNewFile();
        }
        outputStream = new FileOutputStream(outFile);
        byte[] buffer = new byte[bufferSize];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        inputStream.close();
        outputStream.close();
        return file;
    } catch (IOException e) {
        logger.error("?", e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                logger.error("?", e);
            }
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                logger.error("??", e);
            }
        }
    }
    return file;
}

From source file:org.apache.ofbiz.passport.user.GitHubAuthenticator.java

public static Map<String, Object> getUserInfo(HttpGet httpGet, String accessToken, String tokenType,
        Locale locale) throws AuthenticatorException {
    JSON userInfo = null;// www.  jav  a  2s.com
    httpGet.setConfig(PassportUtil.StandardRequestConfig);
    CloseableHttpClient jsonClient = HttpClients.custom().build();
    httpGet.setHeader(PassportUtil.AUTHORIZATION_HEADER, tokenType + " " + accessToken);
    httpGet.setHeader(PassportUtil.ACCEPT_HEADER, "application/json");
    CloseableHttpResponse getResponse = null;
    try {
        getResponse = jsonClient.execute(httpGet);
        String responseString = new BasicResponseHandler().handleResponse(getResponse);
        if (getResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // Debug.logInfo("Json Response from GitHub: " + responseString, module);
            userInfo = JSON.from(responseString);
        } else {
            String errMsg = UtilProperties.getMessage(resource, "GetOAuth2AccessTokenError",
                    UtilMisc.toMap("error", responseString), locale);
            throw new AuthenticatorException(errMsg);
        }
    } catch (ClientProtocolException e) {
        throw new AuthenticatorException(e.getMessage());
    } catch (IOException e) {
        throw new AuthenticatorException(e.getMessage());
    } finally {
        if (getResponse != null) {
            try {
                getResponse.close();
            } catch (IOException e) {
                // do nothing
            }
        }
    }
    JSONToMap jsonMap = new JSONToMap();
    Map<String, Object> userMap;
    try {
        userMap = jsonMap.convert(userInfo);
    } catch (ConversionException e) {
        throw new AuthenticatorException(e.getMessage());
    }
    return userMap;
}

From source file:utils.APIImporter.java

/**
 * Update the documents of a existing API
 * @param uuid uudi of the API/*  ww  w. j av a2  s  .co  m*/
 * @param apiId api id of the API(provider-name-version)
 * @param token access token
 * @param folderPath folder path to the imported folder
 */
private static void updateAPIDocumentation(String uuid, String apiId, String token, String folderPath) {
    //getting the document list of existing API
    String url = config.getPublisherUrl() + "apis/" + uuid + "/documents";
    CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate());
    HttpGet request = new HttpGet(url);
    request.setHeader(HttpHeaders.AUTHORIZATION, ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + token);
    try {
        HttpResponse response = client.execute(request);
        if (response.getStatusLine().getStatusCode() == Response.Status.OK.getStatusCode()) {
            String responseString = EntityUtils.toString(response.getEntity());
            JSONParser parser = new JSONParser();
            JSONObject jsonObj = (JSONObject) parser.parse(responseString);
            JSONArray array = (JSONArray) jsonObj.get(ImportExportConstants.DOC_LIST);
            for (Object anArray : array) {
                JSONObject obj = (JSONObject) anArray;
                String documentId = (String) obj.get(ImportExportConstants.DOC_ID);
                //deleting existing documents
                String deleteUrl = config.getPublisherUrl() + "apis/" + uuid + "/documents/" + documentId;
                CloseableHttpClient httpclient = HttpClientGenerator
                        .getHttpClient(config.getCheckSSLCertificate());
                HttpDelete deleteRequest = new HttpDelete(deleteUrl);
                deleteRequest.setHeader(HttpHeaders.AUTHORIZATION,
                        ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + token);
                httpclient.execute(deleteRequest);
            }
            addAPIDocuments(folderPath, token, uuid);
        } else {
            String status = response.getStatusLine().toString();
            log.error(status);
            System.out.println("error occurred while updating the documents of " + apiId); ////TODO-error msg
        }
    } catch (IOException | ParseException e) {
        errorMsg = "Error occurred while updating the documents of API " + apiId;
        log.error(errorMsg, e);
    }
}