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.ITPersonController.java

private static void add(Person person) throws Exception {
    CTAMSDocument doc = new CTAMSDocument();
    doc.getPeople().add(person);/*w  w w  .j  a v a2 s. c o  m*/
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String xml = XMLUtils.marshal(doc);

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

        for (Person p : doc.getPeople()) {
            if (p.getFirstName().equals(TestFixture.INSTANCE.andy.getFirstName())) {
                TestFixture.INSTANCE.andy.setId(p.getId());
            } else if (p.getFirstName().equals(TestFixture.INSTANCE.bob.getFirstName())) {
                TestFixture.INSTANCE.bob.setId(p.getId());
            } else if (p.getFirstName().equals(TestFixture.INSTANCE.elaine.getFirstName())) {
                TestFixture.INSTANCE.elaine.setId(p.getId());
            } else if (p.getFirstName().equals(TestFixture.INSTANCE.eoin.getFirstName())) {
                TestFixture.INSTANCE.eoin.setId(p.getId());
            } else if (p.getFirstName().equals(TestFixture.INSTANCE.jamie.getFirstName())) {
                TestFixture.INSTANCE.jamie.setId(p.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.vmware.identity.samlservice.impl.SamlServiceImpl.java

/**
 * Utility method to send a slo request to a participant via GET message.
 * @param requestUrl//from   w w w . jav  a2s .  c o  m
 * @throws URISyntaxException
 * @throws IOException
 * @throws ClientProtocolException
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
static void sendSLORequestToOtherParticipant(String requestUrl)
        throws URISyntaxException, ClientProtocolException, IOException, NoSuchAlgorithmException,
        KeyStoreException, KeyManagementException {

    if (requestUrl == null || requestUrl.isEmpty())
        return;

    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(builder.build(),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    URI httpUri = new URI(requestUrl);
    HttpGet httpGet = new HttpGet(httpUri);
    CloseableHttpResponse response = client.execute(httpGet);
    response.close();
}

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

protected static JSONObject getStatisticsJSONObject() throws ScratchStatisticalException {
    try {//w  ww .  ja v a 2s .co  m
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
        debug.setDomain(".scratch.mit.edu");
        debug.setPath("/");
        lang.setDomain(".scratch.mit.edu");
        lang.setPath("/");
        cookieStore.addCookie(debug);
        cookieStore.addCookie(lang);

        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/statistics/data/daily/")
                .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").build();
        try {
            resp = httpClient.execute(update);
        } catch (final IOException e) {
            e.printStackTrace();
            throw new ScratchStatisticalException();
        }

        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        } catch (UnsupportedOperationException | IOException e) {
            e.printStackTrace();
            throw new ScratchStatisticalException();
        }

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        return new JSONObject(result.toString().trim());
    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new ScratchStatisticalException();
    } catch (final Exception e) {
        e.printStackTrace();
        throw new ScratchStatisticalException();
    }
}

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

/**
 * Checks if is passed./*from w w  w.  j a v a  2s  .  c  o  m*/
 *
 * @param endPoint the end point
 * @param testId the test id
 * @param client the client (optional)
 * @return the string
 * @throws Exception
 */
public static String isPassed(String endPoint, String testId, CloseableHttpClient client) throws Exception {

    if (testId == null) {
        throw new Exception("");
    }

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

    try {

        HttpGet request = new HttpGet(endPoint + TestRuns_URL + "/" + testId);

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

        response = client.execute(request);

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

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

            JSONObject jsonRoot = new JSONObject(body);

            try {
                return jsonRoot.getJSONObject("EtfItemCollection").getJSONObject("testRuns")
                        .getJSONObject("TestRun").getString("status");
            } catch (JSONException e) {
                return null;
            }

        } else if (response.getStatusLine().getStatusCode() == 404) {

            throw new NotFoundException("Test not found");

        } else {
            Log.warning(Log.SERVICE, "WARNING: INSPIRE service HTTP response: "
                    + response.getStatusLine().getStatusCode() + " for " + TestRuns_URL + "?view=progress");
        }
    } catch (Exception e) {
        Log.error(Log.SERVICE, "Exception in INSPIRE service: " + endPoint, e);
        throw e;
    } finally {
        if (close) {
            try {
                client.close();
            } catch (IOException e) {
                Log.error(Log.SERVICE, "Error closing CloseableHttpClient: " + endPoint, e);
            }
        }
    }

    return null;
}

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

protected static void add() throws Exception {
    ITVenueController.add();/* w  w w  .  j a  va  2  s . c o m*/
    ITJudgeController.add();
    ITHiredJudgeController.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);

    String xml = XMLUtils.marshal(doc);

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(ITVenueController.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.bandContest.setId(doc.getBandContests().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);
            }
        }
    }

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

    httpPost = new HttpPost(uri);

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

    response = null;

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

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

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

    httpPost = new HttpPost(uri);

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

    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.bandContest.setId(doc.getBandContests().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:eu.ebbitsproject.peoplemanager.utils.HttpUtils.java

public static String findPerson(String errorType, String location) {

    CloseableHttpClient httpClient = HttpClients.createDefault();

    String url = PropertiesUtils.getProperty("uiapp.address");

    HttpPost httpPost = new HttpPost(url);

    List<NameValuePair> nvps = new ArrayList<>();
    nvps.add(new BasicNameValuePair("action", "find-persons"));
    String properties = "demo-e1:competence=" + errorType + ",demo-e1:area-responsibility=" + location;
    String pmProperties = "available=true";
    nvps.add(new BasicNameValuePair("properties", properties));
    nvps.add(new BasicNameValuePair("pmProperties", pmProperties));

    try {/*  w  ww  .j a va 2 s  . com*/
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(HttpUtils.class.getName()).log(Level.SEVERE, null, ex);
    }

    CloseableHttpResponse response = null;
    String personJSON = null;
    try {
        response = httpClient.execute(httpPost);
        personJSON = EntityUtils.toString(response.getEntity());
        System.out.println("######## PersonJSON: " + personJSON);
    } catch (IOException e) {
        Logger.getLogger(HttpUtils.class.getName()).log(Level.SEVERE, null, e);
    } finally {
        try {
            response.close();
        } catch (IOException e) {
            Logger.getLogger(HttpUtils.class.getName()).log(Level.SEVERE, null, e);
        }
    }

    if (personJSON != null) {
        JSONArray persons = (JSONArray) JSONValue.parse(personJSON);
        Iterator<JSONObject> i = persons.iterator();
        if (i.hasNext()) {
            JSONObject o = i.next();
            return o.get("id").toString();
        }
    }

    return personJSON;
}

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

/**
 * Checks if is ready.//from  w w  w.  jav  a  2s. c o  m
 *
 * @param endPoint the end point
 * @param testId the test id
 * @param client the client (optional)
 * @return true, if is ready
 * @throws Exception
 */
public static boolean isReady(String endPoint, String testId, CloseableHttpClient client) throws Exception {

    if (testId == null) {
        return false;
    }

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

    try {

        HttpGet request = new HttpGet(endPoint + TestRuns_URL + "/" + testId + "/progress");

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

        response = client.execute(request);

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

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

            JSONObject jsonRoot = new JSONObject(body);

            // Completed when estimated number of Test Steps is equal to completed Test Steps
            // Somehow this condition is necessary but not sufficient
            // so another check on real value of test is evaluated
            return jsonRoot.getInt("val") == jsonRoot.getInt("max")
                    & InspireValidatorUtils.isPassed(endPoint, testId, client) != null;

        } else if (response.getStatusLine().getStatusCode() == 404) {

            throw new NotFoundException("Test not found");

        } else {
            Log.warning(Log.SERVICE, "WARNING: INSPIRE service HTTP response: "
                    + response.getStatusLine().getStatusCode() + " for " + TestRuns_URL + "?view=progress");
        }
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        Log.error(Log.SERVICE, "Exception in INSPIRE service: " + endPoint, e);
        throw e;
    } finally {
        if (close) {
            try {
                client.close();
            } catch (IOException e) {
                Log.error(Log.SERVICE, "Error closing CloseableHttpClient: " + endPoint, e);
            }
        }
    }

    return false;
}

From source file:org.knoxcraft.http.client.ClientMultipartFormPost.java

public static void upload(String url, String playerName, File jsonfile, File sourcefile)
        throws ClientProtocolException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {// www. j a v a  2  s . c o m
        HttpPost httppost = new HttpPost(url);

        FileBody json = new FileBody(jsonfile);
        FileBody source = new FileBody(sourcefile);
        String jsontext = readFromFile(jsonfile);

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("playerName", new StringBody(playerName, ContentType.TEXT_PLAIN))
                .addPart("jsonfile", json).addPart("sourcefile", source)
                .addPart("language", new StringBody("java", ContentType.TEXT_PLAIN))
                .addPart("jsontext", new StringBody(jsontext, ContentType.TEXT_PLAIN)).addPart("sourcetext",
                        new StringBody("public class Foo {\n  int x=5\n}", ContentType.TEXT_PLAIN))
                .build();

        httppost.setEntity(reqEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            //System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                //System.out.println("Response content length: " + resEntity.getContentLength());
                Scanner sc = new Scanner(resEntity.getContent());
                while (sc.hasNext()) {
                    System.out.println(sc.nextLine());
                }
                sc.close();
                EntityUtils.consume(resEntity);
            }
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

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

/**
 * apache httpclient?post//from   www  .  j  av a  2s.c  om
 * @param url ?
 * @param paramsMap ?map
 * @return ?
 */
public static String doHttpClientPost(String url, Map<String, String> paramsMap) {
    CloseableHttpClient client = HttpClients.createDefault();
    String responseText = "";
    CloseableHttpResponse response = null;
    try {
        HttpPost method = new HttpPost(url);
        if (paramsMap != null) {
            List<NameValuePair> paramList = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> param : paramsMap.entrySet()) {
                NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
                paramList.add(pair);
            }
            method.setEntity(new UrlEncodedFormEntity(paramList, DEFAULT_CHARSET));
        }
        response = client.execute(method);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            responseText = EntityUtils.toString(entity);
        }
    } catch (Exception e) {
        logger.error("?HTTP?", e);
    } finally {
        try {
            response.close();
        } catch (Exception e) {
            logger.error("HTTPResponse?", e);
        }
    }
    return responseText;
}

From source file:BuildArgsIT.java

@Test
public void buildArgsContainerRunsCorrectly() throws Exception {
    String baseUrl = System.getProperty("app.base.url");
    HttpGet get = new HttpGet(baseUrl);
    CloseableHttpClient httpClient = HttpClients.createDefault();

    try (CloseableHttpResponse response = httpClient.execute(get)) {
        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);/*from  w  w w.j ava2 s  .com*/
    }
}