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:ch.ralscha.extdirectspring_itest.MyModelControlerTest.java

private void callMethod(String method) throws IOException, JsonParseException, JsonMappingException {
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("extTID", "3"));
    formparams.add(new BasicNameValuePair("extAction", "myModelController"));
    formparams.add(new BasicNameValuePair("extMethod", method));
    formparams.add(new BasicNameValuePair("extType", "rpc"));
    formparams.add(new BasicNameValuePair("extUpload", "false"));
    formparams.add(new BasicNameValuePair("name", "Jim"));
    UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(formparams, "UTF-8");

    this.post.setEntity(postEntity);

    CloseableHttpResponse response = this.client.execute(this.post);
    try {//from   w w w .  j av  a 2s.com
        HttpEntity entity = response.getEntity();
        assertThat(entity).isNotNull();
        String responseString = EntityUtils.toString(entity);

        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> rootAsMap = mapper.readValue(responseString, Map.class);
        assertThat(rootAsMap).hasSize(5);
        assertThat(rootAsMap.get("method")).isEqualTo(method);
        assertThat(rootAsMap.get("type")).isEqualTo("rpc");
        assertThat(rootAsMap.get("action")).isEqualTo("myModelController");
        assertThat(rootAsMap.get("tid")).isEqualTo(3);

        @SuppressWarnings("unchecked")
        Map<String, Object> result = (Map<String, Object>) rootAsMap.get("result");
        assertThat((Boolean) result.get("success")).isTrue();
    } finally {
        IOUtils.closeQuietly(response);
    }
}

From source file:ch.ralscha.extdirectspring_itest.MyModelServiceTest.java

private void callMethod(String method) throws IOException, JsonParseException, JsonMappingException {
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("extTID", "3"));
    formparams.add(new BasicNameValuePair("extAction", "myModelService"));
    formparams.add(new BasicNameValuePair("extMethod", method));
    formparams.add(new BasicNameValuePair("extType", "rpc"));
    formparams.add(new BasicNameValuePair("extUpload", "false"));
    formparams.add(new BasicNameValuePair("name", "Jim"));
    UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(formparams, "UTF-8");

    this.post.setEntity(postEntity);

    CloseableHttpResponse response = this.client.execute(this.post);
    try {/*from  ww w.j a v a  2  s  . c  o  m*/
        HttpEntity entity = response.getEntity();
        assertThat(entity).isNotNull();
        String responseString = EntityUtils.toString(entity);

        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> rootAsMap = mapper.readValue(responseString, Map.class);
        assertThat(rootAsMap).hasSize(5);
        assertThat(rootAsMap.get("method")).isEqualTo(method);
        assertThat(rootAsMap.get("type")).isEqualTo("rpc");
        assertThat(rootAsMap.get("action")).isEqualTo("myModelService");
        assertThat(rootAsMap.get("tid")).isEqualTo(3);

        @SuppressWarnings("unchecked")
        Map<String, Object> result = (Map<String, Object>) rootAsMap.get("result");
        assertThat((Boolean) result.get("success")).isTrue();
    } finally {
        IOUtils.closeQuietly(response);
    }
}

From source file:justdailscrapper.vik.utility.FetchPageWithoutProxy.java

public static String fetchPageSourcefromClientGoogleSecond(URI newurl, List<ProxyImport> proxyList)
        throws IOException {

    Random r = new Random();

    ProxyImport obj = proxyList.get(r.nextInt(proxyList.size()));

    String ip = obj.proxyIP;/*from   www . j  a va  2 s .  com*/
    int portno = Integer.parseInt(obj.proxyPort);
    String username = "";
    String password = "";
    if (obj.proxyLen > 2) {
        username = obj.proxyUserName;
        password = obj.proxyPassword;
    }

    //        int portNo = generateRandomPort();
    CredentialsProvider credsprovider = new BasicCredentialsProvider();
    credsprovider.setCredentials(new AuthScope(ip, portno),
            new UsernamePasswordCredentials(username, password));
    HttpHost proxy = new HttpHost(ip, portno);
    //-----------------------------------------------------------------------
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).build();

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsprovider)
            .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0")
            .setDefaultRequestConfig(requestConfig).setProxy(proxy).build();
    String responsebody = "";
    String responsestatus = null;
    try {
        HttpGet httpget = new HttpGet(newurl);
        httpget.addHeader("Accept", "*/*");
        httpget.addHeader("Accept-Encoding", "gzip, deflate, br");
        httpget.addHeader("Accept-Language", "en-US,en;q=0.5");
        httpget.addHeader("Host", "www.justdial.com");
        httpget.addHeader("Referer", "https://www.justdial.com/Bangalore/Yamaha-Two-Wheeler-Dealers");
        httpget.addHeader("Connection", "keep-alive");
        httpget.addHeader("X-Requested-With", "XMLHttpReques");

        System.out.println("Response status" + httpget.getRequestLine());
        CloseableHttpResponse resp = httpclient.execute(httpget);
        responsestatus = resp.getStatusLine().toString();
        if (responsestatus.contains("503") || responsestatus.contains("502") || responsestatus.contains("400")
                || responsestatus.contains("401") || responsestatus.contains("402")
                || responsestatus.contains("403") || responsestatus.contains("407")
                || responsestatus.contains("404") || responsestatus.contains("405")
                || responsestatus.contains("SSLHandshakeException") || responsestatus.contains("999")
                || responsestatus.contains("ClientProtocolException")
                || responsestatus.contains("SocketTimeoutException") || responsestatus == null
                || "".equals(responsestatus)) {
            return null;
        } else {
            HttpEntity entity = resp.getEntity();
            System.out.println(resp.getStatusLine());
            if (entity != null) {
                //                    System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    responsebody = new StringBuilder().append(responsebody).append(inputLine).toString();
                }
            }
            EntityUtils.consume(entity);
        }
    } catch (IOException | IllegalStateException e) {
        return null;
    } finally {
        httpclient.close();
    }
    return responsebody;
}

From source file:org.activiti.rest.dmn.service.api.repository.DmnDeploymentResourceTest.java

/**
 * Test getting a single deployment. GET dmn-repository/deployments/{deploymentId}
 *///from w w  w.  ja  va2 s.c  o m
@DmnDeploymentAnnotation(resources = { "org/activiti/rest/dmn/service/api/repository/simple.dmn" })
public void testGetDeployment() throws Exception {
    DmnDeployment existingDeployment = dmnRepositoryService.createDeploymentQuery().singleResult();

    HttpGet httpGet = new HttpGet(SERVER_URL_PREFIX
            + DmnRestUrls.createRelativeResourceUrl(DmnRestUrls.URL_DEPLOYMENT, existingDeployment.getId()));
    CloseableHttpResponse response = executeRequest(httpGet, HttpStatus.SC_OK);
    closeResponse(response);

    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());

    String deploymentId = responseNode.get("id").textValue();
    String name = responseNode.get("name").textValue();
    String category = responseNode.get("category").textValue();
    String deployTime = responseNode.get("deploymentTime").textValue();
    String url = responseNode.get("url").textValue();
    String tenantId = responseNode.get("tenantId").textValue();

    assertEquals("", tenantId);
    assertNotNull(deploymentId);
    assertEquals(existingDeployment.getId(), deploymentId);

    assertNotNull(name);
    assertEquals(existingDeployment.getName(), name);

    assertEquals(existingDeployment.getCategory(), category);

    assertNotNull(deployTime);

    assertNotNull(url);
    assertTrue(url.endsWith(DmnRestUrls.createRelativeResourceUrl(DmnRestUrls.URL_DEPLOYMENT, deploymentId)));
}

From source file:org.flowable.rest.dmn.service.api.repository.DmnDeploymentResourceTest.java

/**
 * Test getting a single deployment. GET dmn-repository/deployments/{deploymentId}
 *//*from   w  ww .ja  v  a  2 s . c om*/
@DmnDeploymentAnnotation(resources = { "org/flowable/rest/dmn/service/api/repository/simple.dmn" })
public void testGetDeployment() throws Exception {
    DmnDeployment existingDeployment = dmnRepositoryService.createDeploymentQuery().singleResult();

    HttpGet httpGet = new HttpGet(SERVER_URL_PREFIX
            + DmnRestUrls.createRelativeResourceUrl(DmnRestUrls.URL_DEPLOYMENT, existingDeployment.getId()));
    CloseableHttpResponse response = executeRequest(httpGet, HttpStatus.SC_OK);
    closeResponse(response);

    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());

    String deploymentId = responseNode.get("id").textValue();
    String name = responseNode.get("name").textValue();
    String category = responseNode.get("category").textValue();
    String deployTime = responseNode.get("deploymentTime").textValue();
    String url = responseNode.get("url").textValue();
    String tenantId = responseNode.get("tenantId").textValue();

    assertEquals("", tenantId);
    assertNotNull(deploymentId);
    assertEquals(existingDeployment.getId(), deploymentId);

    assertNotNull(name);
    assertEquals(existingDeployment.getName(), name);

    assertEquals(existingDeployment.getCategory(), category);

    assertNotNull(deployTime);

    assertNotNull(url);
    assertTrue(url.endsWith(DmnRestUrls.createRelativeResourceUrl(DmnRestUrls.URL_DEPLOYMENT, deploymentId)));
}

From source file:fr.treeptik.cloudunit.service.impl.MonitoringServiceImpl.java

@Override
public String getJsonFromCAdvisor(String containerId) {
    String result = "";
    try {/* w ww. j  a va 2 s  .c  o m*/
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(cAdvisorURL + "/api/v1.0/containers/docker/" + containerId);
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            result = EntityUtils.toString(response.getEntity());
            if (logger.isDebugEnabled()) {
                logger.debug(result);
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        logger.error(containerId, e);
    }
    return result;
}

From source file:fr.treeptik.cloudunit.service.impl.MonitoringServiceImpl.java

@Override
public String getJsonMachineFromCAdvisor() {
    String result = "";
    try {//from w  ww.  ja  v  a2 s  .  c  o  m
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(cAdvisorURL + "/api/v1.0/machine");
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            result = EntityUtils.toString(response.getEntity());
            if (logger.isDebugEnabled()) {
                logger.debug(result);
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        logger.error("" + e);
    }
    return result;
}

From source file:com.abc.turkey.service.unfreeze.UnfreezeProxy.java

public void unfreeze(String number, String ticket, String randstr) throws Exception {
    logger.info("begin unfreezing: " + number);
    // ??// ww  w.  j  ava  2 s. co m
    String checkUrl = "https://aq.qq.com/cn2/ajax/check_verifycode?CaptchaSig=" + ticket + "&account=" + number
            + "&session_type=on_rand&verify_code=" + randstr + "&flag=1&appid=1600000491";
    HttpGet httpGet = new HttpGet(checkUrl);
    CloseableHttpResponse response = httpclient.execute(httpGet);
    String res = EntityUtils.toString(response.getEntity(), "utf8");
    logger.debug(res);
    response.close();

    // ?
    String lockUrl = "https://aq.qq.com/cn2/login_limit/checkstate?from=1&account=" + number + "&verifycode="
            + randstr + "&_=1452372769684";
    httpGet = new HttpGet(lockUrl);
    response = httpclient.execute(httpGet);
    res = EntityUtils.toString(response.getEntity(), "utf8");
    logger.debug(res);
    response.close();
    int lockFlag = JSON.parseObject(res).getIntValue("if_lock");
    if (lockFlag == 0) {
        throw new ServiceException("?");
    }

    // ???
    String smsUrl = "http://aq.qq.com/cn2/login_limit/getsms?verifycode=" + randstr;
    httpGet = new HttpGet(smsUrl);
    response = httpclient.execute(httpGet);
    res = EntityUtils.toString(response.getEntity(), "utf8");
    logger.debug(res);
    response.close();

    // ?
    String smsCode = JSON.parseObject(res).getString("sms");
    smsService.sendSms(smsCode);

    // 
    Thread.sleep(1000);
    int queryTimes = 7;
    while (queryTimes > 0) {
        lockFlag = checkState2(randstr);
        if (lockFlag == 0) {
            break;
        } else {
            if (queryTimes > 3) {
                Thread.sleep(1000);
            } else {
                Thread.sleep(2000);
            }
            queryTimes--;
        }
    }
    if (lockFlag != 0) {
        throw new ServiceException("?");
    }
}

From source file:com.certivox.net.HTTPConnector.java

public HTTPResponse sendRequest(String serviceURL, String http_method, String requestBody,
        Hashtable<String, String> requestProperties) throws IOException {
    HttpRequestBase httpRequest = HttpRequestFactory.createRequest(serviceURL, http_method, requestBody,
            requestProperties);/*from  www . j  ava 2 s. co  m*/
    CloseableHttpResponse response = httpClient.execute(httpRequest, HttpClientContext.create());
    try {
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();
        try {
            return new HTTPResponse(response.getStatusLine().getStatusCode(),
                    StringUtils.convertStreamToString(is));
        } finally {
            is.close();
        }
    } finally {
        response.close();
    }
}

From source file:org.aksw.dice.eaglet.uri.impl.WikipidiaUriChecker.java

public String queryRedirect(String domain, String title) {
    StringBuilder urlBuilder = new StringBuilder(150);
    urlBuilder.append(URL_PROTOCOL_PART);
    urlBuilder.append(domain);//from  w w w.ja v a2 s . com
    urlBuilder.append(URL_QUERY_PART);
    urlBuilder.append(TITLE_ESCAPER.escape(title));

    HttpGet request = null;
    try {
        request = createGetRequest(urlBuilder.toString());
    } catch (IllegalArgumentException e) {
        LOGGER.error("Got an exception while creating a request querying the wiki api of \"" + domain
                + "\". Returning null.", e);
        return null;
    }
    CloseableHttpResponse response = null;
    HttpEntity entity = null;
    try {
        response = sendRequest(request);
        entity = response.getEntity();
        return IOUtils.toString(entity.getContent(), charset);
    } catch (Exception e) {
        LOGGER.error("Got an exception while querying the wiki api of \"" + domain + "\". Returning null.", e);
        return null;
    } finally {
        if (entity != null) {
            try {
                EntityUtils.consume(entity);
            } catch (IOException e1) {
            }
        }
        IOUtils.closeQuietly(response);
        closeRequest(request);
    }
}