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.evrythng.java.wrapper.util.FileUtils.java

/**
 * Uploads a {@code File} with PRIVATE read access.
 *
 * @param uri upload {@link URI}// w w w .  ja v a2s.  com
 * @param contentTypeString content type
 * @param contentFile the file to upload
 * @throws IOException
 */
public static void uploadPrivateContent(final URI uri, final String contentTypeString, final File contentFile)
        throws IOException {

    LOGGER.info("uploadPrivateContent START: uri: [{}]; content type: [{}], content file: [{}]",
            new Object[] { uri, contentTypeString, contentFile });

    CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

    HttpPut httpPut = new HttpPut(uri);
    httpPut.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeString);
    httpPut.addHeader(FileUtils.X_AMZ_ACL_HEADER_NAME, FileUtils.X_AMZ_ACL_HEADER_VALUE_PRIVATE);

    ContentType contentType = ContentType.create(contentTypeString);
    FileEntity fileEntity = new FileEntity(contentFile, contentType);
    httpPut.setEntity(fileEntity);

    CloseableHttpResponse response = closeableHttpClient.execute(httpPut);
    StatusLine statusLine = response.getStatusLine();

    if (!(statusLine.getStatusCode() == HttpStatus.SC_OK)) {
        throw new IOException(String.format("An error occurred while trying to upload private file - %d: %s",
                statusLine.getStatusCode(), statusLine.getReasonPhrase()));
    }

    LOGGER.info("uploadPrivateContent END: uri: [{}]; content type: [{}], content file: [{}]",
            new Object[] { uri, contentTypeString, contentFile });
}

From source file:com.evrythng.java.wrapper.util.FileUtils.java

/**
 * Uploads text as a file content with PRIVATE read access.
 *
 * @param uri upload {@link URI}/*from w  ww.  j a  v a  2s .  co  m*/
 * @param contentTypeString content type
 * @param contentString text content
 * @throws IOException
 */
public static void uploadPrivateContent(final URI uri, final String contentTypeString,
        final String contentString) throws IOException {

    LOGGER.info("uploadPrivateContent START: uri: [{}]; content type: [{}], content length: [{}]",
            new Object[] { uri, contentTypeString, contentString.length() });

    CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

    HttpPut httpPut = new HttpPut(uri);
    httpPut.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeString);
    httpPut.addHeader(FileUtils.X_AMZ_ACL_HEADER_NAME, FileUtils.X_AMZ_ACL_HEADER_VALUE_PRIVATE);

    ContentType contentType = ContentType.create(contentTypeString);
    StringEntity stringEntity = new StringEntity(contentString, contentType);

    httpPut.setEntity(stringEntity);

    CloseableHttpResponse response = closeableHttpClient.execute(httpPut);
    StatusLine statusLine = response.getStatusLine();

    if (!(statusLine.getStatusCode() == HttpStatus.SC_OK)) {
        throw new IOException(String.format("An error occurred while trying to upload private file - %d: %s",
                statusLine.getStatusCode(), statusLine.getReasonPhrase()));
    }

    LOGGER.info("uploadPrivateContent END: uri: [{}]; content type: [{}], content length: [{}]",
            new Object[] { uri, contentTypeString, contentString.length() });
}

From source file:com.networknt.light.server.handler.loader.PageLoader.java

private static void loadPageFile(String host, File file) {
    Scanner scan = null;// w w  w . j av  a2s.  c om
    try {
        scan = new Scanner(file, Loader.encoding);
        // the content is only the data portion. convert to map
        String content = scan.useDelimiter("\\Z").next();
        String pageId = file.getName();
        pageId = pageId.substring(0, pageId.lastIndexOf('.'));
        if (content != null && !content.equals(pageMap.get(pageId))) {
            System.out.println(content);
            System.out.println(pageMap.get(pageId));
            Map<String, Object> inputMap = new HashMap<String, Object>();
            inputMap.put("category", "page");
            inputMap.put("name", "impPage");
            inputMap.put("readOnly", false);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("pageId", pageId);
            data.put("content", content);
            inputMap.put("data", data);
            HttpPost httpPost = new HttpPost(host + "/api/rs");
            httpPost.addHeader("Authorization", "Bearer " + jwt);
            StringEntity input = new StringEntity(
                    ServiceLocator.getInstance().getMapper().writeValueAsString(inputMap));
            input.setContentType("application/json");
            httpPost.setEntity(input);
            CloseableHttpResponse response = httpclient.execute(httpPost);

            try {
                System.out.println("Page: " + file.getAbsolutePath() + " is loaded with status "
                        + response.getStatusLine());
                HttpEntity entity = response.getEntity();
                BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
                String json = "";
                String line = "";
                while ((line = rd.readLine()) != null) {
                    json = json + line;
                }
                //System.out.println("json = " + json);
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } else {
            //System.out.println("Skip file " + pageId);
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        if (scan != null)
            scan.close();
    }
}

From source file:com.linecorp.armeria.server.http.file.HttpFileServiceTest.java

private static void assertStatusLine(CloseableHttpResponse res, String expectedStatusLine) {
    assertThat(res.getStatusLine().toString(), is(expectedStatusLine));
}

From source file:com.precioustech.fxtrading.oanda.restapi.OandaTestUtils.java

public static final void mockHttpInteraction(String fname, HttpClient mockHttpClient) throws Exception {
    CloseableHttpResponse mockResp = mock(CloseableHttpResponse.class);
    when(mockHttpClient.execute(any(HttpUriRequest.class))).thenReturn(mockResp);

    HttpEntity mockEntity = mock(HttpEntity.class);

    when(mockResp.getEntity()).thenReturn(mockEntity);

    StatusLine mockStatusLine = mock(StatusLine.class);

    when(mockResp.getStatusLine()).thenReturn(mockStatusLine);
    when(mockStatusLine.getStatusCode()).thenReturn(HttpStatus.SC_OK);
    when(mockEntity.getContent()).thenReturn(new FileInputStream(fname));
}

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

/**
 * Do get./*w ww. j  ava2 s .c  om*/
 *
 * @param uri
 *            the uri
 * @param headers
 *            the headers
 * @return the string
 * @throws ClientProtocolException
 *             the client protocol exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws HttpResponseException
 *             the http response exception
 */
public static HttpGetSimpleResp doGet(String uri, HashMap<String, String> headers)
        throws ClientProtocolException, IOException, HttpResponseException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGetSimpleResp resp = new HttpGetSimpleResp();
    try {
        HttpGet httpGet = new HttpGet(uri);
        for (String key : headers.keySet()) {
            httpGet.addHeader(key, headers.get(key));
        }
        CloseableHttpResponse response = httpclient.execute(httpGet);
        resp.setStatusCode(response.getStatusLine().getStatusCode());
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            try {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    // TODO to use for performance in the future
                    // ResponseHandler<String> handler = new BasicResponseHandler();
                    resp.setResult(new BasicResponseHandler().handleResponse(response));
                }
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } else {
            // TODO optimiz (repeating code)
            throw new HttpResponseException(response.getStatusLine().getStatusCode(),
                    response.getStatusLine().getReasonPhrase());
        }
    } finally {
        httpclient.close();
    }
    return resp;
}

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

/**
 * Do delete./*from  w  w  w. j a va2s  .  c  om*/
 *
 * @param uri the uri
 * @param headers the headers
 * @return the http get simple resp
 * @throws ClientProtocolException the client protocol exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws HttpResponseException the http response exception
 */
public static HttpGetSimpleResp doDelete(String uri, HashMap<String, String> headers)
        throws ClientProtocolException, IOException, HttpResponseException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGetSimpleResp resp = new HttpGetSimpleResp();
    try {
        HttpDelete httpDelete = new HttpDelete(uri);
        for (String key : headers.keySet()) {
            httpDelete.addHeader(key, headers.get(key));
        }
        CloseableHttpResponse response = httpclient.execute(httpDelete);

        resp.setStatusCode(response.getStatusLine().getStatusCode());
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT) {
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    // TODO to use for performance in the future
                    resp.setResult(new BasicResponseHandler().handleResponse(response));
                }
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } else {
            // TODO optimiz (repeating code)
            throw new HttpResponseException(response.getStatusLine().getStatusCode(),
                    response.getStatusLine().getReasonPhrase());
        }
    } finally {
        httpclient.close();
    }
    return resp;
}

From source file:com.clonephpscrapper.utility.FetchPageWithProxy.java

public static String fetchPageSourcefromClientGoogleSecond(URI newurl) throws IOException {

    int portNo = generateRandomPort();
    CredentialsProvider credsprovider = new BasicCredentialsProvider();
    credsprovider.setCredentials(new AuthScope("195.154.161.103", portNo),
            new UsernamePasswordCredentials("mongoose", "Fjh30fi"));
    HttpHost proxy = new HttpHost("195.154.161.103", 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 {/*from ww w  . j ava  2  s  .  co m*/
        HttpGet httpget = new HttpGet(newurl);
        httpget.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        httpget.addHeader("Accept-Encoding", "gzip, deflate");
        httpget.addHeader("Accept-Language", "en-US,en;q=0.5");
        httpget.addHeader("Connection", "keep-alive");

        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();
                }
                // writeResponseFile(responsebody, pagename);
            }
            EntityUtils.consume(entity);
        }
    } catch (IOException | IllegalStateException e) {
        return null;
    } finally {
        httpclient.close();
    }
    return responsebody;
}

From source file:org.commonjava.maven.galley.transport.htcli.internal.util.TransferResponseUtils.java

public static boolean handleUnsuccessfulResponse(final HttpUriRequest request,
        final CloseableHttpResponse response, HttpLocation location, final String url,
        final boolean graceful404) throws TransferException {
    final Logger logger = LoggerFactory.getLogger(TransferResponseUtils.class);

    final StatusLine line = response.getStatusLine();
    InputStream in = null;/*w w  w. ja  v  a  2  s . co m*/
    HttpEntity entity = null;
    try {
        entity = response.getEntity();
        final int sc = line.getStatusCode();
        boolean contentMissing = (sc == HttpStatus.SC_NOT_FOUND || sc == HttpStatus.SC_GONE);

        if (graceful404 && contentMissing) {
            return false;
        } else {
            ByteArrayOutputStream out = null;
            if (entity != null) {
                in = entity.getContent();
                out = new ByteArrayOutputStream();
                copy(in, out);
            }

            if (NON_SERVER_GATEWAY_ERRORS.contains(sc) || (sc > 499 && sc < 599)) {
                throw new BadGatewayException(location, url, sc, "HTTP request failed: %s%s", line,
                        (out == null ? "" : "\n\n" + new String(out.toByteArray())));
            } else if (contentMissing) {
                throw new TransferException("HTTP request failed: %s\nURL: %s%s", line, url,
                        (out == null ? "" : "\n\n" + new String(out.toByteArray())));
            } else {
                throw new TransferLocationException(location, "HTTP request failed: %s%s", line,
                        (out == null ? "" : "\n\n" + new String(out.toByteArray())));
            }
        }
    } catch (final IOException e) {
        request.abort();
        throw new TransferLocationException(location,
                "Error reading body of unsuccessful request.\nStatus: %s.\nURL: %s.\nReason: %s", e, line, url,
                e.getMessage());
    } finally {
        IOUtils.closeQuietly(in);
        if (entity != null) {
            try {
                EntityUtils.consume(entity);
            } catch (final IOException e) {
                logger.debug("Failed to consume entity: " + e.getMessage(), e);
            }
        }
    }
}

From source file:com.wattzap.model.social.SelfLoopsAPI.java

public static int uploadActivity(String email, String passWord, String fileName, String note)
        throws IOException {
    JSONObject jsonObj = null;/*  w w  w  .  j a  v  a 2  s .  c  o m*/

    FileInputStream in = null;
    GZIPOutputStream out = null;
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("enctype", "multipart/mixed");

        in = new FileInputStream(fileName);
        // Create stream to compress data and write it to the to file.
        ByteArrayOutputStream obj = new ByteArrayOutputStream();
        out = new GZIPOutputStream(obj);

        // Copy bytes from one stream to the other
        byte[] buffer = new byte[4096];
        int bytes_read;
        while ((bytes_read = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytes_read);
        }
        out.close();
        in.close();

        ByteArrayBody bin = new ByteArrayBody(obj.toByteArray(), ContentType.create("application/x-gzip"),
                fileName);
        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("email", new StringBody(email, ContentType.TEXT_PLAIN))
                .addPart("pw", new StringBody(passWord, ContentType.TEXT_PLAIN)).addPart("tcxfile", bin)
                .addPart("note", new StringBody(note, ContentType.TEXT_PLAIN)).build();

        httpPost.setEntity(reqEntity);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            int code = response.getStatusLine().getStatusCode();
            switch (code) {
            case 200:

                HttpEntity respEntity = response.getEntity();

                if (respEntity != null) {
                    // EntityUtils to get the response content
                    String content = EntityUtils.toString(respEntity);
                    //System.out.println(content);
                    JSONParser jsonParser = new JSONParser();
                    jsonObj = (JSONObject) jsonParser.parse(content);
                }

                break;
            case 403:
                throw new RuntimeException(
                        "Authentification failure " + email + " " + response.getStatusLine());
            default:
                throw new RuntimeException("Error " + code + " " + response.getStatusLine());
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
        }

        int activityId = ((Long) jsonObj.get("activity_id")).intValue();

        // parse error code
        int error = ((Long) jsonObj.get("error_code")).intValue();
        if (activityId == -1) {
            String message = (String) jsonObj.get("message");
            switch (error) {
            case 102:
                throw new RuntimeException("Empty TCX file " + fileName);
            case 103:
                throw new RuntimeException("Invalide TCX Format " + fileName);
            case 104:
                throw new RuntimeException("TCX Already Present " + fileName);
            case 105:
                throw new RuntimeException("Invalid XML " + fileName);
            case 106:
                throw new RuntimeException("invalid compression algorithm");
            case 107:
                throw new RuntimeException("Invalid file mime types");
            default:
                throw new RuntimeException(message + " " + error);
            }
        }

        return activityId;
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
        httpClient.close();
    }
}