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.ebaysf.ostara.upgrade.util.GitUtils.java

private static StringBuilder readData(Set<String> committers, String url)
        throws IOException, ClientProtocolException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    BufferedReader br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));

    if (response1.getStatusLine().getStatusCode() != 200) {
        LOG.warn("Unable to get git committers for " + url + " status code is "
                + response1.getStatusLine().getStatusCode());
        return null;
    }//from w w w  .  j  av  a 2 s.  c  o  m

    StringBuilder sb = new StringBuilder();
    String output;
    while ((output = br.readLine()) != null) {
        sb.append(output);
    }
    return sb;
}

From source file:com.bbc.util.ClientCustomSSL.java

public static String clientCustomSLL(String mchid, String path, String data) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");

    System.out.println("?...");
    FileInputStream instream = new FileInputStream(new File("/payment/apiclient_cert.p12"));
    try {//  w  w w  .j  a v  a2 s.  co  m
        keyStore.load(instream, mchid.toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mchid.toCharArray()).build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpPost httpost = new HttpPost(path);
        httpost.addHeader("Connection", "keep-alive");
        httpost.addHeader("Accept", "*/*");
        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpost.addHeader("Host", "api.mch.weixin.qq.com");
        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
        httpost.addHeader("Cache-Control", "max-age=0");
        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");

        httpost.setEntity(new StringEntity(data, "UTF-8"));
        CloseableHttpResponse response = httpclient.execute(httpost);
        try {
            HttpEntity entity = response.getEntity();
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                StringBuffer sb = new StringBuffer("");
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                    sb.append(text);
                }
                return sb.toString();

            }
            EntityUtils.consume(entity);
            return "";
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:eionet.gdem.utils.HttpUtils.java

/**
 * Method checks whether the resource behind the given URL exist. The method calls HEAD request and if the resonse code is 200,
 * then returns true. If exception is thrown or response code is something else, then the result is false.
 *
 * @param url URL// w  w  w . j  a  va2s. c  o  m
 * @return True if resource behind the url exists.
 */
public static boolean urlExists(String url) {

    CloseableHttpClient client = HttpClients.createDefault();

    // Create a method instance.
    HttpHead method = new HttpHead(url);
    CloseableHttpResponse response = null;
    try {
        // Execute the method.
        response = client.execute(method);
        int statusCode = response.getStatusLine().getStatusCode();
        return statusCode == HttpStatus.SC_OK;
        /*} catch (HttpException e) {
            LOGGER.error("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
            return false;*/
    } catch (IOException e) {
        LOGGER.error("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        return false;
    } finally {
        // Release the connection.
        method.releaseConnection();
        try {
            response.close();
        } catch (IOException e) {
            // do nothing
        }
    }
}

From source file:com.ibm.watson.movieapp.dialog.rest.UtilityFunctions.java

/**
 * Parses response to JSON object/*  w  ww.ja v  a2s.co m*/
 * <p>
 * This extracts a JSON object response from a CloseableHttpResponse.</p>
 * 
 * @param response the CloseableHttpResponse
 * @return the JSON object response
 * @throws IllegalStateException if the response stream cannot be parsed correctly
 * @throws IOException if it is unable to parse the response
 * @throws HttpException if the HTTP call responded with a status code other than 200 or 201
 */
public static JsonObject parseHTTPResponse(CloseableHttpResponse response, String uri)
        throws IllegalStateException, IOException, HttpException {
    int statusCode = response.getStatusLine().getStatusCode();

    // Messages.setInfo(response.getLocale());
    if (statusCode != 200 && statusCode != 201) {
        logger.error(MessageFormat.format(Messages.getString("UtilityFunctions.HTTP_STATUS"), //$NON-NLS-1$
                response.getStatusLine().getStatusCode(), uri));
        throw new HttpException(MessageFormat.format(Messages.getString("UtilityFunctions.HTTP_STATUS"),
                response.getStatusLine().getStatusCode(), uri));
    }
    HttpEntity entity = response.getEntity();
    String strResponse = EntityUtils.toString(entity);
    JsonElement je = new JsonParser().parse(strResponse);
    JsonObject jo = je.getAsJsonObject();
    return jo;
}

From source file:com.ibm.devops.notification.MessageHandler.java

public static void postToWebhook(String webhook, boolean deployableMessage, JSONObject message,
        PrintStream printStream) {
    //check webhook
    if (Util.isNullOrEmpty(webhook)) {
        printStream.println("[IBM Cloud DevOps] IBM_CLOUD_DEVOPS_WEBHOOK_URL not set.");
        printStream.println("[IBM Cloud DevOps] Error: Failed to notify OTC.");
    } else {/*from  w ww .  ja va2 s. com*/
        // set a 5 seconds timeout
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(5000)
                .setConnectTimeout(5000).setConnectionRequestTimeout(5000).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig)
                .build();
        HttpPost postMethod = new HttpPost(webhook);
        try {
            StringEntity data = new StringEntity(message.toString());
            postMethod.setEntity(data);
            postMethod = Proxy.addProxyInformation(postMethod);
            postMethod.addHeader("Content-Type", "application/json");

            if (deployableMessage) {
                postMethod.addHeader("x-create-connection", "true");
                printStream.println("[IBM Cloud DevOps] Sending Deployable Mapping message to webhook:");
                printStream.println(message);
            }

            CloseableHttpResponse response = httpClient.execute(postMethod);

            if (response.getStatusLine().toString().matches(".*2([0-9]{2}).*")) {
                printStream.println("[IBM Cloud DevOps] Message successfully posted to webhook.");
            } else {
                printStream.println(
                        "[IBM Cloud DevOps] Message failed, response status: " + response.getStatusLine());
            }
        } catch (IOException e) {
            printStream.println("[IBM Cloud DevOps] IOException, could not post to webhook:");
            e.printStackTrace(printStream);
        }
    }
}

From source file:com.oakhole.voa.utils.HttpClientUtils.java

/**
 * ??/*from   www  .  j  a  v  a  2  s  .  c  o m*/
 *
 * @param uri
 * @param params
 * @return
 */
public static String post(String uri, String params) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(uri);
    StringEntity stringEntity = new StringEntity(params, CHARSET.toString());
    httpPost.setEntity(stringEntity);
    try {
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            httpResponse.close();
            return EntityUtils.toString(httpResponse.getEntity(), CHARSET);
        }
    } catch (IOException e) {
        logger.error(":{}", e.getMessage());
    }
    return "";
}

From source file:com.hy.utils.pay.wx.ClientCustomSSL.java

public static void test() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("D:/10016225.p12"));
    try {//from w  w  w  . j a v a  2  s .c o  m
        keyStore.load(instream, "10016225".toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "10016225".toCharArray()).build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");

        System.out.println("executing request" + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                }

            }
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.ecofactor.qa.automation.consumerapi.dr.HTTPSClient.java

/**
 * Gets the response./*  w w  w  . j a va  2  s.c  o  m*/
 *
 * @param url the url
 * @param httpClient the http client
 * @return the response
 */
public static synchronized HttpResponse getResponse(final String url, final CloseableHttpClient httpClient) {

    try {
        checkHTTPClient(httpClient);
        final HttpGet httpPost = new HttpGet(url);
        httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        httpPost.setHeader(HttpHeaders.ACCEPT, "application/json");

        final CloseableHttpResponse response = httpClient.execute(httpPost);
        setLogString("Status == " + response.getStatusLine(), true);
        return response;

    } catch (IOException | HTTPClientException e) {
        setLogString("Error executing HTTPS method. Reason ::: " + e, true);
        return null;
    }
}

From source file:com.ecofactor.qa.automation.consumerapi.dr.HTTPSClient.java

/**
 * Put response./*ww w  .j  a v  a2 s.  c  o  m*/
 *
 * @param url the url
 * @param json the json
 * @param httpClient the http client
 * @return the http response
 */
public static synchronized HttpResponse putResponse(final String url, final String json,
        final CloseableHttpClient httpClient) {

    try {
        checkHTTPClient(httpClient);
        final HttpPut httpPut = new HttpPut(url);
        httpPut.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        httpPut.setHeader(HttpHeaders.ACCEPT, "application/json");

        final StringEntity params = new StringEntity(json);
        httpPut.setEntity(params);

        final CloseableHttpResponse response = httpClient.execute(httpPut);
        setLogString("Status == " + response.getStatusLine(), true);
        return response;

    } catch (IOException | HTTPClientException e) {
        setLogString("Error executing HTTPS method. Reason ::: " + e, true);
        return null;
    }
}

From source file:com.ecofactor.qa.automation.consumerapi.dr.HTTPSClient.java

/**
 * Post response.//from ww w .  j a va2  s.  c  om
 *
 * @param url the url
 * @param json the json
 * @param httpClient the http client
 * @return the http response
 */
public static synchronized HttpResponse postResponse(final String url, final String json,
        final CloseableHttpClient httpClient) {

    try {
        checkHTTPClient(httpClient);
        final HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        httpPost.setHeader(HttpHeaders.ACCEPT, "application/json");

        final StringEntity params = new StringEntity(json);
        httpPost.setEntity(params);

        final CloseableHttpResponse response = httpClient.execute(httpPost);
        setLogString("Status == " + response.getStatusLine(), true);
        return response;

    } catch (IOException | HTTPClientException e) {
        setLogString("Error executing HTTPS method. Reason ::: " + e, true);
        return null;
    }
}