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

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

Introduction

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

Prototype

StatusLine getStatusLine();

Source Link

Usage

From source file:org.wso2.carbon.dynamic.client.web.proxy.OAuthEndpointProxy.java

@POST
@Consumes("application/x-www-form-urlencoded")
@Produces("application/json")
public Response issueAccessToken(MultivaluedMap<String, String> paramMap) {
    DefaultHttpClient httpClient = DCRProxyUtils.getHttpsClient();
    String host = DCRProxyUtils.getKeyManagerHost();
    Response response;/*from w w  w.j  a  v a 2  s  .  c  o  m*/
    try {
        URI uri = new URIBuilder().setScheme(Constants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_PROTOCOL)
                .setHost(host).setPath(Constants.RemoteServiceProperties.OAUTH2_TOKEN_ENDPOINT).build();
        HttpHost httpHost = new HttpHost(uri.toString());
        CloseableHttpResponse serverResponse = httpClient.execute(httpHost, null);
        HttpEntity responseData = serverResponse.getEntity();
        int status = serverResponse.getStatusLine().getStatusCode();
        String resp = EntityUtils.toString(responseData, Constants.CharSets.CHARSET_UTF_8);
        response = Response.status(DCRProxyUtils.getResponseStatus(status)).entity(resp).build();
    } catch (URISyntaxException | IOException e) {
        String msg = "Service invoke error occurred while registering client";
        log.error(msg, e);
        response = Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
    } finally {
        httpClient.close();
    }
    return response;
}

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

/**
 * Test retrieving all projects./*from   ww  w . j  ava2s.c om*/
 * @throws MLHttpClientException 
 * @throws IOException 
 */
@Test(description = "Retrieve a project")
public void testGetAllProjects() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient.doHttpGet("/api/projects");
    assertEquals("Unexpected response recieved", Response.Status.OK.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:ar.edu.ubp.das.src.chat.actions.LogoutAction.java

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        String authToken = String.valueOf(request.getSession().getAttribute("token"));

        HttpPost httpPost = new HttpPost("http://25.136.78.82:8080/logout/");
        httpPost.addHeader("Authorization", "BEARER " + authToken);
        httpPost.addHeader("accept", "application/json");

        CloseableHttpResponse postResponse = httpClient.execute(httpPost);

        HttpEntity responseEntity = postResponse.getEntity();
        StatusLine responseStatus = postResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException(restResp);
        }/*from  w  w w .  ja v  a  2 s.  c  o  m*/

        request.getSession().removeAttribute("token");

        return mapping.getForwardByName("success");

    } catch (IOException | RuntimeException e) {
        request.setAttribute("message", "Error al realizar logout: " + e.getMessage());
        response.setStatus(400);
        return mapping.getForwardByName("failure");
    }
}

From source file:org.jasig.cas.web.LicenceFilter.java

public void init(FilterConfig config) throws ServletException {
    //licence/* w  ww.  j  a v  a2s .  co m*/
    String liurl = config.getInitParameter("liurl");
    if (liurl == null || liurl.isEmpty()) {
        throw new ServletException();
    }
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(liurl);
    httpGet.addHeader("accept", "application/json");
    CloseableHttpResponse response1 = null;
    try {
        response1 = httpclient.execute(httpGet);
        if (response1.getStatusLine().getStatusCode() != 200) {
            System.out.println("licence ");
            throw new ServletException();
        }
        HttpEntity entity1 = response1.getEntity();
        BufferedReader br = new BufferedReader(new InputStreamReader((entity1.getContent())));
        String output;
        StringBuilder sb = new StringBuilder();
        while ((output = br.readLine()) != null) {
            sb.append(output);
        }
        JSONObject jsonObject = new JSONObject(sb.toString());
        String error = jsonObject.getString("code");
        if (!error.equals("S_OK")) {
            System.out.println("licence ");
            throw new ServletException();
        }
        String strexprietime = jsonObject.getJSONObject("var").getJSONObject("licInfo").getString("expireTime");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        this.expiretime = df.parse(strexprietime).getTime();
        EntityUtils.consume(entity1);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            response1.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:callAPIHelper.CallApiHelper.java

public String CallAPIForURL(DataURL dataUrl, RowDataFromFile data)
        throws UnsupportedEncodingException, IOException {

    String code = "";
    String POST_URL = dataUrl.getUrl();
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(POST_URL);

    httpPost.setHeader("Content-type", dataUrl.getContentType());
    httpPost.setHeader("Accept-Content Type", dataUrl.getAcceptType());
    JsonObject jdata = data.getData();// www  .  j av a2s .c  om
    System.out.println("data post: " + jdata.toString());
    httpPost.setEntity(new StringEntity(jdata.toString()));
    CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
    if (httpResponse.getStatusLine().getStatusCode() == 200) {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(httpResponse.getEntity().getContent()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();
        JsonObject jresp = new JsonObject();
        jresp = gson.fromJson(response.toString(), JsonObject.class);
        System.out.println("data resp: " + jresp.toString());
        //            JsonElement je = jresp.get("code");
        code = jresp.toString();
    } else {
        System.out.println("API Fail status code = " + httpResponse.getStatusLine().getStatusCode());
        //            return new DataResponseWithdrawFunds();/
        code = "-1";
    }
    return code;
}

From source file:co.paralleluniverse.comsat.webactors.AbstractWebActorTest.java

@Test
public void testHttpMsg() throws IOException, InterruptedException, ExecutionException {
    final HttpGet httpGet = new HttpGet("http://localhost:8080");
    try (final CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(requestConfig)
            .build()) {/*  w  w  w . j a  v  a2  s .  c  om*/
        final CloseableHttpResponse res = client.execute(httpGet);
        assertEquals(200, res.getStatusLine().getStatusCode());
        assertEquals("text/html", res.getFirstHeader("Content-Type").getValue());
        assertEquals("12", res.getFirstHeader("Content-Length").getValue());
        assertEquals("httpResponse", EntityUtils.toString(res.getEntity()));
    }
}

From source file:org.superbiz.AuthBeanTest.java

private String get(final String user, final String password) {
    final BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
    basicCredentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
    final CloseableHttpClient client = HttpClients.custom()
            .setDefaultCredentialsProvider(basicCredentialsProvider).build();

    final HttpHost httpHost = new HttpHost(webapp.getHost(), webapp.getPort(), webapp.getProtocol());
    final AuthCache authCache = new BasicAuthCache();
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(httpHost, basicAuth);//from  w w  w.ja  va2  s .co  m
    final HttpClientContext context = HttpClientContext.create();
    context.setAuthCache(authCache);

    final HttpGet get = new HttpGet(webapp.toExternalForm() + "servlet");
    CloseableHttpResponse response = null;
    try {
        response = client.execute(httpHost, get, context);
        return response.getStatusLine().getStatusCode() + " " + EntityUtils.toString(response.getEntity());
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    } finally {
        try {
            IO.close(response);
        } catch (final IOException e) {
            // no-op
        }
    }
}

From source file:com.networknt.exception.ExceptionHandlerTest.java

@Test
public void testNormal() throws Exception {
    String url = "http://localhost:8080/normal";
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    try {//from   w  w w .  j ava2  s . com
        CloseableHttpResponse response = client.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        Assert.assertEquals(200, statusCode);
        if (statusCode == 200) {
            String s = IOUtils.toString(response.getEntity().getContent(), "utf8");
            Assert.assertNotNull(s);
            Assert.assertEquals("normal", s);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.networknt.swagger.SwaggerHandlerTest.java

@Test
public void testWrongPath() throws Exception {
    // this path is not in petstore swagger specification. get error
    String url = "http://localhost:8080/get";
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    try {/*from   w  w  w . ja  v  a  2s  .co  m*/
        CloseableHttpResponse response = client.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        Assert.assertEquals(404, statusCode);
        if (statusCode == 404) {
            Status status = Config.getInstance().getMapper().readValue(response.getEntity().getContent(),
                    Status.class);
            Assert.assertNotNull(status);
            Assert.assertEquals("ERR10007", status.getCode());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.networknt.swagger.SwaggerHandlerTest.java

@Test
public void testWrongMethod() throws Exception {
    // this path is not in petstore swagger specification. get error
    String url = "http://localhost:8080/v2/pet";
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    try {// ww  w.j a  v  a2s.  co m
        CloseableHttpResponse response = client.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        Assert.assertEquals(405, statusCode);
        if (statusCode == 405) {
            Status status = Config.getInstance().getMapper().readValue(response.getEntity().getContent(),
                    Status.class);
            Assert.assertNotNull(status);
            Assert.assertEquals("ERR10008", status.getCode());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}