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:com.ecofactor.qa.automation.consumerapi.dr.HTTPSClient.java

/**
 * Patch response.//from  w w w .  j a v a  2  s.  c om
 *
 * @param url the url
 * @param json the json
 * @param httpClient the http client
 * @return the http response
 */
public static synchronized HttpResponse patchResponse(final String url, final String json,
        final CloseableHttpClient httpClient) {

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

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

        final CloseableHttpResponse response = httpClient.execute(httpPatch);
        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.ibm.streamsx.topology.internal.streaminganalytics.RestUtils.java

public static JsonObject getGsonResponse(CloseableHttpClient httpClient, HttpRequestBase request)
        throws IOException, ClientProtocolException {
    request.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType());

    CloseableHttpResponse response = httpClient.execute(request);
    JsonObject jsonResponse;/*from   ww w .j  a  v a 2 s .c  o m*/
    try {
        HttpEntity entity = response.getEntity();
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            final String errorInfo;
            if (entity != null)
                errorInfo = " -- " + EntityUtils.toString(entity);
            else
                errorInfo = "";
            throw new IllegalStateException(
                    "Unexpected HTTP resource from service:" + response.getStatusLine().getStatusCode() + ":"
                            + response.getStatusLine().getReasonPhrase() + errorInfo);
        }

        if (entity == null)
            throw new IllegalStateException("No HTTP resource from service");

        Reader r = new InputStreamReader(entity.getContent());
        jsonResponse = new Gson().fromJson(r, JsonObject.class);
        EntityUtils.consume(entity);
    } finally {
        response.close();
    }
    return jsonResponse;
}

From source file:org.ambraproject.wombat.controller.WombatController.java

protected static void forwardAssetResponse(CloseableHttpResponse remoteResponse,
        HttpServletResponse responseToClient, boolean isDownloadRequest) throws IOException {
    if (remoteResponse.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_NOT_MODIFIED) {
        responseToClient.setStatus(org.apache.http.HttpStatus.SC_NOT_MODIFIED);
    } else {/*from   ww w . j a  v  a  2s  . c om*/
        HttpMessageUtil.copyResponseWithHeaders(remoteResponse, responseToClient,
                getAssetResponseHeaderFilter(isDownloadRequest));
    }
}

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

/**
 * Downloads remote file// ww w.j a v  a 2 s .c  om
 * @param url URL
 * @return Downloaded file
 * @throws DCMException If an error occurs.
 * @throws IOException If an error occurs.
 */
public static byte[] downloadRemoteFile(String url) throws DCMException, IOException {
    byte[] responseBody = null;
    CloseableHttpClient client = HttpClients.createDefault();

    // Create a method instance.
    HttpGet method = new HttpGet(url);
    // Execute the method.
    CloseableHttpResponse response = null;
    try {
        response = client.execute(method);
        HttpEntity entity = response.getEntity();
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode != HttpStatus.SC_OK) {
            LOGGER.error("Method failed: " + response.getStatusLine().getReasonPhrase());
            throw new DCMException(BusinessConstants.EXCEPTION_SCHEMAOPEN_ERROR,
                    response.getStatusLine().getReasonPhrase());
        }

        // Read the response body.
        InputStream instream = entity.getContent();
        responseBody = IOUtils.toByteArray(instream);

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        // System.out.println(new String(responseBody));
        /*catch (HttpException e) {
        LOGGER.error("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
        throw e;*/
    } catch (IOException e) {
        LOGGER.error("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        throw e;
    } finally {
        // Release the connection.
        response.close();
        method.releaseConnection();
        client.close();
    }
    return responseBody;
}

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  va 2 s. com
 * @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:org.jenkinsci.plugins.fabric8.support.RestClient.java

public static String parse(CloseableHttpResponse response) throws IOException {
    try {//from  w  w w  . jav a2 s .c  o m
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuilder builder = new StringBuilder();
        builder.append("status: " + response.getStatusLine());
        String line = "";
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
            builder.append(line);
            builder.append("/n");
        }
        return builder.toString();
    } finally {
        response.close();
    }
}

From source file:com.rtl.http.Upload.java

private static String send(String message, InputStream fileIn, String url) throws Exception {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000)
            .build();// 
    post.setConfig(requestConfig);//  w  ww.  ja va2 s.  com
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setCharset(Charset.forName("UTF-8"));// ?
    ContentType contentType = ContentType.create("text/html", "UTF-8");
    builder.addPart("reqParam", new StringBody(message, contentType));
    builder.addPart("version", new StringBody("1.0", contentType));
    builder.addPart("dataFile", new InputStreamBody(fileIn, "file"));
    post.setEntity(builder.build());
    CloseableHttpResponse response = client.execute(post);
    InputStream inputStream = null;
    String responseStr = "", sCurrentLine = "";
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        inputStream = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((sCurrentLine = reader.readLine()) != null) {
            responseStr = responseStr + sCurrentLine;
        }
        return responseStr;
    }
    return null;
}

From source file:org.duracloud.syncui.SyncUIDriver.java

private static boolean isAppRunning(String url, CloseableHttpClient client) {
    HttpGet get = new HttpGet(url);
    CloseableHttpResponse response;
    int responseCode;
    try {/*from  www  .  j  av a2  s.c o  m*/
        response = client.execute(get);
        responseCode = response.getStatusLine().getStatusCode();
    } catch (IOException e) {
        log.debug("Attempt to connect to synctool app at url " + url + " failed due to: " + e.getMessage());
        responseCode = 0;
    }
    log.debug("Response from {}: {}", url, responseCode);
    return responseCode == 200;
}

From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java

/**
 * Do post.//from   w w w  . j a v  a  2  s.  c o m
 *
 * @param uri
 *            the uri
 * @param body
 *            the body
 * @param headers
 *            the headers
 * @return the int
 * @throws ClientProtocolException
 *             the client protocol exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws HttpResponseException
 *             the http response exception
 */
public static int doPost(String uri, String body, HashMap<String, String> headers)
        throws ClientProtocolException, IOException, HttpResponseException {
    // TODO delete before commit
    // System.out.println("doPost>> uri:"+uri +"\nbody:"+body+"\n");
    CloseableHttpClient httpclient = HttpClients.createDefault();
    int resp = -1;
    try {
        HttpPost httpPost = new HttpPost(uri);
        for (String key : headers.keySet()) {
            httpPost.addHeader(key, headers.get(key));
            // System.out.println("header:"+key+"/"+headers.get(key));

        }
        // System.out.println("doPost<<");
        httpPost.setEntity(new StringEntity(body));
        CloseableHttpResponse response = httpclient.execute(httpPost);
        resp = response.getStatusLine().getStatusCode();
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            response.close();
        } else {
            throw new HttpResponseException(response.getStatusLine().getStatusCode(),
                    response.getStatusLine().getReasonPhrase());
        }
    } finally {
        httpclient.close();
    }
    return resp;
}

From source file:net.palette_software.pet.restart.HelperHttpClient.java

static void modifyWorker(String targetURL, BalancerManagerManagedWorker w, HashMap<String, Integer> switches,
        int simulation) throws Exception {
    try (CloseableHttpClient client = HttpClients.createDefault()) {

        if (!(simulation < 1)) {
            return;
        }//from  ww  w .  ja  va 2s .c  o m

        //connect to Balancer Manager
        HttpPost httpPost = new HttpPost(targetURL);

        List<NameValuePair> params = new ArrayList<>();

        //check the switches map for the keys are acceptable to interact with Balancer Manager
        for (Map.Entry<String, Integer> entry : switches.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue().toString();
            if (!BalancerManagerAcceptedPostKeysContains(key)) {
                HelperLogger.loggerStdOut.info("Bad key in modifyWorker (" + key + "," + value + ")");
                continue;
            }
            params.add(new BasicNameValuePair(key, value));
        }

        //add the necessary parameters
        params.add(new BasicNameValuePair("b", w.getBalancerMemberName()));
        params.add(new BasicNameValuePair("w", w.getName()));
        params.add(new BasicNameValuePair("nonce", w.getNonce()));
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        //send the request
        CloseableHttpResponse response = client.execute(httpPost);

        //throw an exception is the result status is abnormal.
        int responseCode = response.getStatusLine().getStatusCode();
        if (200 != responseCode) {
            throw new Exception("Balancer-manager returned a http response of " + responseCode);
        }
    }
}