Example usage for org.apache.http.client.methods CloseableHttpResponse getEntity

List of usage examples for org.apache.http.client.methods CloseableHttpResponse getEntity

Introduction

In this page you can find the example usage for org.apache.http.client.methods CloseableHttpResponse getEntity.

Prototype

HttpEntity getEntity();

Source Link

Usage

From source file:com.calmio.calm.integration.Helpers.HTTPHandler.java

public static HTTPResponseData sendPost(String url, String body, String username, String pwd) throws Exception {

    CloseableHttpClient client = HttpClients.custom()
            .setDefaultCredentialsProvider(getCredentialsProvider(url, username, pwd)).build();

    int responseCode = 0;
    StringBuffer respo = null;//from ww w . ja v a  2s  . com
    String userPassword = username + ":" + pwd;
    //        String encoding = Base64.getEncoder().encodeToString(userPassword.getBytes());
    String encoding = Base64.encodeBase64String(userPassword.getBytes());

    try {
        HttpPost request = new HttpPost(url);
        request.addHeader("Authorization", "Basic " + encoding);
        request.addHeader("User-Agent", USER_AGENT);
        request.addHeader("Accept-Language", "en-US,en;q=0.5");
        request.addHeader("Content-Type", "application/json; charset=UTF-8");
        request.setHeader("Accept", "application/json");
        System.out.println("Executing request " + request.getRequestLine());
        System.out.println("Executing request " + Arrays.toString(request.getAllHeaders()));
        StringEntity se = new StringEntity(body);
        request.setEntity(se);
        CloseableHttpResponse response = client.execute(request);
        try {
            responseCode = response.getStatusLine().getStatusCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post body : " + body);
            System.out.println("Response Code : " + responseCode);
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            respo = new StringBuffer();
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                respo.append(inputLine);
            }
        } finally {
            response.close();
        }
    } finally {
        client.close();
    }

    HTTPResponseData result = new HTTPResponseData(responseCode, ((respo == null) ? "" : respo.toString()));
    System.out.println(result.getStatusCode() + "/n" + result.getBody());
    return result;
}

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

/**
 * Send request by post method./*from w w w  .ja  va 2s.  com*/
 * 
 * @param uri:
 *            http://ip:port/demo
 */
public static String doPostJson(String uri, String data) {
    String result = "";
    try {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
            httpPost.setEntity(new StringEntity(data, ContentType.create("text/json", "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 json request has error, msg is " + e.getMessage());
    }

    return result;
}

From source file:tradeok.HttpTool.java

/**
 * HTTPS5S/* w  w  w.  j  a  v a2 s .  c o  m*/
 *
 * @param reqURL
 * @param params
 * @return
 */
public static String connectPostHttps(String reqURL, Map<String, String> params) {

    String responseContent = null;

    HttpPost httpPost = new HttpPost(reqURL);
    try {
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(connectTimeout)
                .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectTimeout).build();

        List<NameValuePair> formParams = new ArrayList<NameValuePair>();
        httpPost.setEntity(new UrlEncodedFormEntity(formParams, Consts.UTF_8));
        httpPost.setConfig(requestConfig);
        //  Entry
        for (Map.Entry<String, String> entry : params.entrySet()) {
            formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        CloseableHttpResponse response = httpclient.execute(httpPost);
        try {
            // POST
            HttpEntity entity = response.getEntity(); // ??
            try {
                if (null != entity) {
                    responseContent = EntityUtils.toString(entity, Consts.UTF_8);
                }
            } finally {
                if (entity != null) {
                    entity.getContent().close();
                }
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
        System.out.printf("\ninfo:requestURI : " + httpPost.getURI() + ", responseContent: " + responseContent);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        System.out.printf("\nerror:ClientProtocolException", e);
    } catch (IOException e) {
        e.printStackTrace();
        System.out.printf("\nerror:IOException", e);
    } finally {
        httpPost.releaseConnection();
    }
    return responseContent;

}

From source file:com.comcast.viper.hlsparserj.PlaylistFactory.java

/**
 * Returns a playlist inputStream given an httpClient and a URL.
 * @param httpClient http client//from   w  ww  .j  a v  a  2  s  .c o  m
 * @param url URL to a playlist
 * @return inputStream
 * @throws IOException on HTTP connection exception
 */
private static InputStream getPlaylistInputStream(final CloseableHttpClient httpClient, final URL url)
        throws IOException {
    HttpGet get = new HttpGet(url.toString());
    CloseableHttpResponse response = null;
    response = httpClient.execute(get);
    if (response == null) {
        throw new IOException("Request returned a null response");
    }
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        response.close();
        throw new IOException("Request returned a status code of " + response.getStatusLine().getStatusCode());
    }

    return response.getEntity().getContent();
}

From source file:zz.pseas.ghost.login.weibo.SinaWeiboLogin.java

public static String getSinaCookie(String username, String password) throws Exception {

    StringBuilder sb = new StringBuilder();
    HtmlUnitDriver driver = new HtmlUnitDriver(true);
    // driver.setSocksProxy("127.0.0.1", 1080);
    // driver.setProxy("127.0.0.1", 1080);
    // HtmlOption htmlOption=new Ht
    // WebDriver driver = new FirefoxDriver();
    driver.setJavascriptEnabled(true);/*from  w  w  w .  ja va 2  s.co  m*/
    // user agent switcher//
    String loginAddress = "http://login.weibo.cn/login/";
    driver.get(loginAddress);
    WebElement ele = driver.findElementByCssSelector("img");
    String src = ele.getAttribute("src");
    String cookie = concatCookie(driver);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000).setConnectTimeout(1000)
            .setCookieSpec(cookie).build();

    HttpGet httpget = new HttpGet(src);
    httpget.setConfig(requestConfig);
    CloseableHttpResponse response = httpclient.execute(httpget);

    HttpEntity entity;
    String result = null;
    try {

        if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) {
            // try again//
        }
        entity = response.getEntity();

        if (entity != null) {
            InputStream instream = entity.getContent();
            try {
                // do something useful
                InputStream inputStream = entity.getContent();
                BufferedImage img = ImageIO.read(inputStream);
                // deal with the weibo captcha //
                String picName = LoginUtils.getCurrentTime("yyyyMMdd-hhmmss");
                // captcha//
                LoginUtils.getCaptchaDir();
                picName = "./captcha/captcha-" + picName + ".png";
                ImageIO.write(img, "png", new File(picName));
                String userInput = new CaptchaFrame(img).getUserInput();
                WebElement mobile = driver.findElementByCssSelector("input[name=mobile]");
                mobile.sendKeys(username);
                WebElement pass = driver.findElementByCssSelector("input[name^=password]");
                pass.sendKeys(password);
                WebElement code = driver.findElementByCssSelector("input[name=code]");
                code.sendKeys(userInput);
                WebElement rem = driver.findElementByCssSelector("input[name=remember]");
                rem.click();
                WebElement submit = driver.findElementByCssSelector("input[name=submit]");
                // ?//
                submit.click();
                result = concatCookie(driver);
                driver.close();
            } finally {
                instream.close();
            }
        }
    } finally {
        response.close();
    }

    if (result.contains("gsid_CTandWM")) {
        return result;
    } else {
        // throw new Exception("weibo login failed");
        return null;
    }
}

From source file:DeliverWork.java

private static String getResultBody(String url) {
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;
    String resultBody = null;//from w  w w .j av a2s.com
    try {
        httpClient = HttpClients.createDefault();
        // http(get?)
        HttpGet httpget = new HttpGet(url);
        response = httpClient.execute(httpget);
        HttpEntity result = response.getEntity();
        resultBody = EntityUtils.toString(result);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (response != null) {
                response.close();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    return resultBody;
}

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

private static void add() throws Exception {
    ITVenueController.add();/*  www.j  av  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();//  ww  w. jav  a 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:org.xwiki.contrib.repository.pypi.internal.utils.PyPiHttpUtils.java

public static InputStream performGet(URI uri, HttpClientFactory httpClientFactory, HttpContext localContext)
        throws HttpException {
    HttpGet getMethod = new HttpGet(uri);
    CloseableHttpClient httpClient = httpClientFactory.createClient(null, null);
    CloseableHttpResponse response;
    try {// ww w .  j  av a2 s.  c  om
        if (localContext != null) {
            response = httpClient.execute(getMethod, localContext);
        } else {
            response = httpClient.execute(getMethod);
        }
    } catch (Exception e) {
        throw new HttpException(String.format("Failed to request [%s]", getMethod.getURI()), e);
    }

    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_OK) {
        try {
            return response.getEntity().getContent();
        } catch (IOException e) {
            throw new HttpException(
                    String.format("Failed to parse response body of request [%s]", getMethod.getURI()), e);
        }
    } else if (statusCode == HttpStatus.SC_NOT_FOUND) {
        return null;
    } else {
        throw new HttpException(String.format("Invalid answer [%s] from the server when requesting [%s]",
                response.getStatusLine().getStatusCode(), getMethod.getURI()));
    }
}

From source file:org.pepstock.jem.commands.util.HttpUtil.java

/**
 * Calls a http node of JEM to get all members of group, necessary to client
 * to connect to JEM.//  w w w. ja  v a 2  s.  c om
 * 
 * @param url http URL to call
 * @return Arrays with all members of Hazelcast cluster
 * @throws SubmitException if errors occur
 */
public static String[] getMembers(String url) throws SubmitException {
    // creates a HTTP client
    CloseableHttpClient httpclient = null;
    try {
        httpclient = createHttpClient(url);
        // concats URL with query string
        String completeUrl = url + HttpUtil.MEMBERS_QUERY_STRING;
        // prepares GET request and basic response handler
        HttpGet httpget = new HttpGet(completeUrl);
        CloseableHttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            long len = entity.getContentLength();
            if (len != -1 && len < 2048) {
                // executes and parse the results
                // result must be
                // [ipaddress:port],[ipaddress:port],[ipaddress:port],....[ipaddress:port]
                return EntityUtils.toString(entity).trim().split(",");
            } else {
                throw new IOException("HTTP Entity content length wrong: " + len);
            }
        }
        throw new IOException("HTTP Entity is null");
    } catch (KeyManagementException e) {
        throw new SubmitException(SubmitMessage.JEMW001E, e);
    } catch (UnrecoverableKeyException e) {
        throw new SubmitException(SubmitMessage.JEMW001E, e);
    } catch (NoSuchAlgorithmException e) {
        throw new SubmitException(SubmitMessage.JEMW001E, e);
    } catch (KeyStoreException e) {
        throw new SubmitException(SubmitMessage.JEMW001E, e);
    } catch (URISyntaxException e) {
        throw new SubmitException(SubmitMessage.JEMW001E, e);
    } catch (ClientProtocolException e) {
        throw new SubmitException(SubmitMessage.JEMW001E, e);
    } catch (IOException e) {
        throw new SubmitException(SubmitMessage.JEMW001E, e);
    } finally {
        // close http client
        if (httpclient != null) {
            try {
                httpclient.close();
            } catch (IOException e) {
                LogAppl.getInstance().ignore(e.getMessage(), e);
            }
        }
    }
}