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

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

Introduction

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

Prototype

public void close() throws IOException;

Source Link

Document

Closes this stream and releases any system resources associated with it.

Usage

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

private void login() {
    try {//from  ww  w.ja  va  2  s.  com
        HttpPost httpPost = new HttpPost(loginUrl);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("username", "yuzhibo468"));
        nvps.add(new BasicNameValuePair("password", "qq123654"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        CloseableHttpResponse response = httpclient.execute(httpPost);
        String res = EntityUtils.toString(response.getEntity(), "utf8");
        logger.debug(res);
        response.close();
    } catch (Exception e) {
        throw new ServiceException("Sms api login error!");
    }
}

From source file:org.wildfly.test.integration.microprofile.health.MicroProfileHealthSecuredHTTPEndpointTestCase.java

@Test
public void securedHTTPEndpoint() throws Exception {
    final String healthURL = "http://" + managementClient.getMgmtAddress() + ":"
            + managementClient.getMgmtPort() + "/health";

    try (CloseableHttpClient client = HttpClients.createDefault()) {

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials("testSuite", "testSuitePassword"));
        HttpClientContext hcContext = HttpClientContext.create();
        hcContext.setCredentialsProvider(credentialsProvider);

        CloseableHttpResponse resp = client.execute(new HttpGet(healthURL), hcContext);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        String content = MicroProfileHealthHTTPEndpointTestCase.getContent(resp);
        resp.close();
        assertTrue("'UP' message is expected", content.contains("UP"));
    }//from   w w w  .j a v  a  2  s .c o m
}

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

private synchronized String getNextDid() throws Exception {
    int posInList = numberIndex / 3; // ????3
    if (didList != null && posInList < didList.size()) {
        numberIndex++;/*w ww  .ja  v  a 2s .c  o m*/
        return didList.get(posInList);
    }
    if (phoneList == null) {
        // ??
        HttpGet httpGet = new HttpGet(releaseUrl);
        CloseableHttpResponse response = httpclient.execute(httpGet);
        String res = EntityUtils.toString(response.getEntity(), "utf8");
        response.close();
        logger.debug(res);
        checkRes(res, httpGet);
    } else {
        // ??
        String blackUrl = "http://www.7tds.com/api/order/toblacklist?pid=33WXXZWP6LYN&phones=";
        for (int i = 0; i < phoneList.size(); i++) {
            if (i == 0) {
                blackUrl += phoneList.get(i);
            } else {
                blackUrl += (',' + phoneList.get(i));
            }
        }
        HttpGet httpGet = new HttpGet(blackUrl);
        CloseableHttpResponse response = httpclient.execute(httpGet);
        String res = EntityUtils.toString(response.getEntity(), "utf8");
        response.close();
        logger.debug("to blackList res:" + res);
        checkRes(res, httpGet);
    }

    // ?oid
    HttpGet httpGet = new HttpGet(fetchUrl);
    CloseableHttpResponse response = httpclient.execute(httpGet);
    String res = EntityUtils.toString(response.getEntity(), "utf8");
    response.close();
    res = checkRes(res, httpGet);
    String orderId = JSON.parseObject(res).getString("order_id");

    // ?did
    httpGet = new HttpGet("http://www.7tds.com/api/order/result?&oid=" + orderId);
    response = httpclient.execute(httpGet);
    res = EntityUtils.toString(response.getEntity(), "utf8");
    response.close();
    res = checkRes(res, httpGet);
    logger.debug(res);

    JSONArray array = JSON.parseObject(res).getJSONArray("rows");
    didList = new ArrayList<String>();
    for (int i = 0; i < array.size(); i++) {
        didList.add(array.getJSONObject(i).getString("order_detail_id"));
    }
    // ?
    numberIndex = 1;
    return didList.get(0);
}

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);
    // ??// w w  w . j  a va  2  s  .c  o 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:org.wso2.carbon.ml.analysis.test.GetAnalysesTestCase.java

/**
 * Test retrieving all analyzes.//from www .  j a v a  2s. co m
 * 
 * @throws MLHttpClientException
 * @throws IOException
 */
@Test(description = "Get all analyses")
public void testGetAllAnalyzes() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient.doHttpGet("/api/analyses/");
    assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:org.superbiz.CdiEventRealmTest.java

@Test
public void badAuthentication() throws IOException {
    final CloseableHttpClient client = HttpClients.createDefault();

    // first authenticate with the login servlet
    final HttpPost httpPost = new HttpPost(webapp.toExternalForm() + "login");
    final List<NameValuePair> data = new ArrayList<NameValuePair>() {
        {/*from w  ww .j a va2 s  . c om*/
            add(new BasicNameValuePair("username", "userB"));
            add(new BasicNameValuePair("password", "bla bla"));
        }
    };
    httpPost.setEntity(new UrlEncodedFormEntity(data));
    final CloseableHttpResponse respLogin = client.execute(httpPost);
    try {
        assertEquals(401, respLogin.getStatusLine().getStatusCode());

    } finally {
        respLogin.close();
    }
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.DeliveryServicesTest.java

@Test
public void itReturnsBadRequestForBadUrlQueryParameter() throws Exception {
    String encodedUrl = "httptrafficrouter01somedeliveryservicesomecdndomainfoo/stuff";
    HttpGet httpGet = new HttpGet("http://localhost:3333/crs/deliveryservices?url=" + encodedUrl);

    CloseableHttpResponse response = null;
    try {/*from   ww w  .j  av a2s. c om*/
        response = closeableHttpClient.execute(httpGet);
        assertThat(response.getStatusLine().getStatusCode(), equalTo(400));
    } finally {
        if (response != null)
            response.close();
    }
}

From source file:org.wso2.carbon.ml.project.test.GetProjectsTestCase.java

/**
 * Test retrieving a project.//w w  w .jav  a 2s.c  om
 * @throws MLHttpClientException 
 * @throws IOException 
 */
@Test(description = "Retrieve a project")
public void testGetProject() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient
            .doHttpGet("/api/projects/" + MLIntegrationTestConstants.PROJECT_NAME);
    assertEquals("Unexpected response recieved", Response.Status.OK.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.DeliveryServicesTest.java

@Test
public void itReturnsNotFoundForNonexistentDeliveryService() throws Exception {
    String encodedUrl = URLEncoder.encode("http://trafficrouter01.somedeliveryservice.somecdn.domain.foo/stuff",
            "utf-8");
    HttpGet httpGet = new HttpGet("http://localhost:3333/crs/deliveryservices?url=" + encodedUrl);

    CloseableHttpResponse response = null;
    try {/*from www  . ja va 2s  .  c om*/
        response = closeableHttpClient.execute(httpGet);
        assertThat(response.getStatusLine().getStatusCode(), equalTo(404));
    } finally {
        if (response != null)
            response.close();
    }
}

From source file:com.srotya.tau.nucleus.qa.QAAlertRules.java

@Test
public void testCHTTPAlertRules() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException,
        ClientProtocolException, IOException, InterruptedException {
    wireMockRule.addStubMapping(stubFor(post(urlEqualTo("/alert")).willReturn(
            aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody("na"))));
    CloseableHttpClient client = null;//  ww w . j a  v  a2 s  .  c  o  m
    client = Utils.buildClient("http://localhost:8080/commands/templates", 2000, 2000);
    HttpPut templateUpload = new HttpPut("http://localhost:8080/commands/templates");
    String template = AlertTemplateSerializer.serialize(new AlertTemplate((short) 3, "test_template",
            "http://localhost:54322/alert", "http", "test", "test", 30, 1), false);
    templateUpload.addHeader("content-type", "application/json");
    templateUpload.setEntity(new StringEntity(new Gson().toJson(new TemplateCommand("all", false, template))));
    CloseableHttpResponse response = client.execute(templateUpload);
    response.close();
    assertTrue(
            response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300);

    client = Utils.buildClient("http://localhost:8080/commands/rules", 2000, 2000);
    HttpPut ruleUpload = new HttpPut("http://localhost:8080/commands/rules");
    String rule = RuleSerializer.serializeRuleToJSONString(new SimpleRule((short) 4, "SimpleRule", true,
            new EqualsCondition("value", 3.0), new Action[] { new TemplatedAlertAction((short) 0, (short) 3) }),
            false);
    ruleUpload.addHeader("content-type", "application/json");
    ruleUpload.setEntity(new StringEntity(
            new Gson().toJson(new RuleCommand(StatelessRulesEngine.ALL_RULEGROUP, false, rule))));
    response = client.execute(ruleUpload);
    response.close();
    assertTrue(
            response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300);

    client = Utils.buildClient("http://localhost:8080/events", 2000, 2000);
    Map<String, Object> eventHeaders = new HashMap<>();
    eventHeaders.put("value", 3);
    eventHeaders.put("@timestamp", "2014-04-23T13:40:29.000Z");
    eventHeaders.put(Constants.FIELD_EVENT_ID, 1102);

    HttpPost eventUpload = new HttpPost("http://localhost:8080/events");
    eventUpload.addHeader("content-type", "application/json");
    eventUpload.setEntity(new StringEntity(new Gson().toJson(eventHeaders)));
    response = client.execute(eventUpload);
    response.close();
    assertTrue(response.getStatusLine().getReasonPhrase(),
            response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300);
    Thread.sleep(1000);
    verify(1, postRequestedFor(urlEqualTo("/alert")));
}