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.drftpd.util.HttpUtils.java

public static String retrieveHttpAsString(String url) throws HttpException, IOException {
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig)
            .setUserAgent(_userAgent).build();
    HttpGet httpGet = new HttpGet(url);
    httpGet.setConfig(requestConfig);/*from w  ww .  j a  va2s  . c  o  m*/
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httpGet);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            throw new HttpException("Error " + statusCode + " for URL " + url);
        }
        HttpEntity entity = response.getEntity();
        String data = EntityUtils.toString(entity);
        EntityUtils.consume(entity);
        return data;
    } catch (IOException e) {
        throw new IOException("Error for URL " + url, e);
    } finally {
        if (response != null) {
            response.close();
        }
        httpclient.close();
    }
}

From source file:com.vmware.identity.rest.core.client.RequestExecutor.java

private static <T> T executeInternal(CloseableHttpClient client, HttpUriRequest request, JavaType type)
        throws ClientProtocolException, WebApplicationException, HttpException, IOException {
    CloseableHttpResponse response = client.execute(request);

    try {//from   w w  w .  ja  v a 2s  .  c  o m
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NO_CONTENT) {
            return handleSuccess(response, type);
        } else {
            throw handleError(response, response.getStatusLine().getStatusCode());
        }
    } finally {
        response.close();
    }
}

From source file:com.farsunset.cim.util.MessageDispatcher.java

private static String httpPost(String url, Message msg) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);

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

    nvps.add(new BasicNameValuePair("mid", msg.getMid()));
    nvps.add(new BasicNameValuePair("extra", msg.getExtra()));
    nvps.add(new BasicNameValuePair("action", msg.getAction()));
    nvps.add(new BasicNameValuePair("title", msg.getTitle()));
    nvps.add(new BasicNameValuePair("content", msg.getContent()));
    nvps.add(new BasicNameValuePair("sender", msg.getSender()));
    nvps.add(new BasicNameValuePair("receiver", msg.getReceiver()));
    nvps.add(new BasicNameValuePair("timestamp", String.valueOf(msg.getTimestamp())));

    httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
    CloseableHttpResponse response2 = httpclient.execute(httpPost);
    String data = null;/*from w w w .j a v  a 2  s.c  o m*/
    try {
        System.out.println(response2.getStatusLine());
        HttpEntity entity2 = response2.getEntity();
        data = EntityUtils.toString(entity2);
    } finally {
        response2.close();
    }

    return data;
}

From source file:com.calmio.calm.integration.Helpers.HTTPHandler.java

public static HTTPResponseData sendGet(String url, String username, String pwd) throws Exception {
    CloseableHttpClient client = HttpClients.custom()
            .setDefaultCredentialsProvider(getCredentialsProvider(url, username, pwd)).build();

    int responseCode = 0;
    StringBuffer respo = null;// w ww  .  ja va  2  s.  c o  m
    String userPassword = username + ":" + pwd;
    //        String encoding = Base64.getEncoder().encodeToString(userPassword.getBytes());
    String encoding = Base64.encodeBase64String(userPassword.getBytes());

    try {
        HttpGet request = new HttpGet(url);
        request.addHeader("Authorization", "Basic " + encoding);
        request.addHeader("User-Agent", USER_AGENT);
        System.out.println("Executing request " + request.getRequestLine());
        CloseableHttpResponse response = client.execute(request);
        try {
            responseCode = response.getStatusLine().getStatusCode();
            System.out.println("\nSending 'GET' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            respo = new StringBuffer();
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                respo.append(inputLine);
            }
        } finally {
            response.close();
        }
    } finally {
        client.close();
    }

    HTTPResponseData result = new HTTPResponseData(responseCode, ((respo == null) ? "" : respo.toString()));
    System.out.println(result.getStatusCode() + "/n" + result.getBody());
    return result;
}

From source file:fridgegameinstaller.MCJsonConf.java

public static void getJson(String path, int mb) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet("http://api.fridgegame.com/mcconf/Fridgegame.json");

    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    try {//from   w ww .jav a2s.  c  om
        System.out.println(httpGet.toString());
        System.out.println(response1.getStatusLine());
        BufferedReader br = new BufferedReader(new InputStreamReader(response1.getEntity().getContent()));
        String a;
        String output = "";
        while ((a = br.readLine()) != null) {
            output += a + "\n";
        }
        System.out.println(output);
        try {

            JSONObject json = new JSONObject(output);
            String mcArgs = json.getString("minecraftArguments");
            String regex = "(-Xmx[^ ]*)";
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(mcArgs);
            String newArgs = m.replaceAll("-Xmx" + mb + "M");
            json.put("minecraftArguments", newArgs);
            FileWriter file = new FileWriter(path);

            try {
                file.write(json.toString());

            } catch (IOException e) {
                e.printStackTrace();

            } finally {
                file.flush();
                file.close();
            }

        } catch (JSONException e) {

        }
    } finally {
        response1.close();
    }

}

From source file:com.seleniumtests.browserfactory.SauceLabsDriverFactory.java

/**
 * Upload application to saucelabs server
 * @param targetAppPath//from   w w  w  . j  av a2 s  .com
 * @param serverURL
 * @return
 * @throws IOException
 * @throws AuthenticationException 
 */
protected static boolean uploadFile(String targetAppPath) throws IOException, AuthenticationException {

    // extract user name and password from getWebDriverGrid
    Matcher matcher = REG_USER_PASSWORD
            .matcher(SeleniumTestsContextManager.getThreadContext().getWebDriverGrid().get(0));
    String user;
    String password;
    if (matcher.matches()) {
        user = matcher.group(1);
        password = matcher.group(2);
    } else {
        throw new ConfigurationException(
                "getWebDriverGrid variable does not have the right format for connecting to sauceLabs");
    }

    FileEntity entity = new FileEntity(new File(targetAppPath));
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);

    HttpPost request = new HttpPost(String.format(SAUCE_UPLOAD_URL, user, new File(targetAppPath).getName()));
    request.setEntity(entity);
    request.addHeader(new BasicScheme().authenticate(creds, request, null));
    request.addHeader("Content-Type", "application/octet-stream");

    try (CloseableHttpClient client = HttpClients.createDefault();) {
        CloseableHttpResponse response = client.execute(request);

        if (response.getStatusLine().getStatusCode() != 200) {
            client.close();
            throw new ConfigurationException(
                    "Application file upload failed: " + response.getStatusLine().getReasonPhrase());
        }
    }

    return true;
}

From source file:org.keycloak.testsuite.util.URLAssert.java

public static void assertGetURL(URI url, String accessToken, AssertResponseHandler handler) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from   ww  w  .  j  av  a 2s . co  m*/
        HttpGet get = new HttpGet(url);
        get.setHeader("Authorization", "Bearer " + accessToken);

        CloseableHttpResponse response = httpclient.execute(get);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Response status error: " + response.getStatusLine().getStatusCode() + ": " + url);
        }

        handler.assertResponse(response);

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.calmio.calm.integration.Helpers.HTTPHandler.java

public static HTTPResponseData sendPost(String url, String body, String username, String pwd) throws Exception {

    CloseableHttpClient client = HttpClients.custom()
            .setDefaultCredentialsProvider(getCredentialsProvider(url, username, pwd)).build();

    int responseCode = 0;
    StringBuffer respo = null;//w ww  .ja  va2 s  . c om
    String userPassword = username + ":" + pwd;
    //        String encoding = Base64.getEncoder().encodeToString(userPassword.getBytes());
    String encoding = Base64.encodeBase64String(userPassword.getBytes());

    try {
        HttpPost request = new HttpPost(url);
        request.addHeader("Authorization", "Basic " + encoding);
        request.addHeader("User-Agent", USER_AGENT);
        request.addHeader("Accept-Language", "en-US,en;q=0.5");
        request.addHeader("Content-Type", "application/json; charset=UTF-8");
        request.setHeader("Accept", "application/json");
        System.out.println("Executing request " + request.getRequestLine());
        System.out.println("Executing request " + Arrays.toString(request.getAllHeaders()));
        StringEntity se = new StringEntity(body);
        request.setEntity(se);
        CloseableHttpResponse response = client.execute(request);
        try {
            responseCode = response.getStatusLine().getStatusCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post body : " + body);
            System.out.println("Response Code : " + responseCode);
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            respo = new StringBuffer();
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                respo.append(inputLine);
            }
        } finally {
            response.close();
        }
    } finally {
        client.close();
    }

    HTTPResponseData result = new HTTPResponseData(responseCode, ((respo == null) ? "" : respo.toString()));
    System.out.println(result.getStatusCode() + "/n" + result.getBody());
    return result;
}

From source file:com.aws.sampleImage.url.TestHttpGetFlickrAPI.java

private static String callFlickrAPIForEachKeyword(String query) throws IOException, JSONException {
    String apiKey = "ad4f88ecfd53b17f93178e19703fe00d";
    String apiSecret = "96cab0e9f89468d6";

    int totalPages = 4;

    int total = 500;
    int perPage = 500;

    int counter = 0;

    int currentCount = 0;

    for (int i = 1; i <= totalPages && currentCount <= total; i++, currentCount = currentCount + perPage) {

        String url = "https://api.flickr.com/services/rest/?method=flickr.photos.search&text=" + query
                + "&extras=url_c,url_m,url_n,license,owner_name&per_page=500&page=" + i
                + "&format=json&api_key=" + apiKey + "&api_secret=" + apiSecret + "&license=4,5,6,7,8";

        System.out.println("URL FORMED --> " + url);

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

        System.out.println("GET Response Status:: " + httpResponse.getStatusLine().getStatusCode());

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(httpResponse.getEntity().getContent()));

        String inputLine;/*  w  w w.ja  v  a2  s  . c  o m*/
        StringBuffer response = new StringBuffer();

        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();

        String responseString = response.toString();

        responseString = responseString.replace("jsonFlickrApi(", "");

        int length = responseString.length();

        responseString = responseString.substring(0, length - 1);

        // print result
        System.out.println("After making it a valid JSON --> " + responseString);
        httpClient.close();

        JSONObject json = null;
        try {
            json = new JSONObject(responseString);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //System.out.println("Converted JSON String " + json);

        JSONObject photosObj = json.has("photos") ? json.getJSONObject("photos") : null;
        total = photosObj.has("total") ? (Integer.parseInt(photosObj.getString("total"))) : 0;
        perPage = photosObj.has("perpage") ? (Integer.parseInt(photosObj.getString("perpage"))) : 0;

        System.out.println(" perPage --> " + perPage + " total --> " + total);

        JSONArray photoArr = photosObj.getJSONArray("photo");
        System.out.println("Length of Array --> " + photoArr.length());
        String scrapedImageURL = "";

        for (int itr = 0; itr < photoArr.length(); itr++) {
            JSONObject tempObject = photoArr.getJSONObject(itr);
            scrapedImageURL = tempObject.has("url_c") ? tempObject.getString("url_c")
                    : tempObject.has("url_m") ? tempObject.getString("url_m")
                            : tempObject.has("url_n") ? tempObject.getString("url_n") : "";

            //System.out.println("Scraped Image URL --> " + scrapedImageURL);

            counter++;
        }

    }

    System.out.println("C O U N T E R -> " + counter);
    return null;
}

From source file:org.dbrane.cloud.util.httpclient.HttpClientHelper.java

/**
 * ?Http//from  w  w w .  j  a v a  2  s .com
 * 
 * @param request
 * @return
 */
private static String getResult(HttpRequestBase request) {
    CloseableHttpClient httpClient = getHttpClient();
    try {
        CloseableHttpResponse response = httpClient.execute(request);
        response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity);
            response.close();
            if (200 == response.getStatusLine().getStatusCode()) {
                return result;
            } else {
                throw new BaseException(ErrorType.Httpclient, result);
            }
        }
        return EMPTY_STR;
    } catch (Exception e) {
        logger.debug(ErrorType.Httpclient.toString(), e);
        throw new BaseException(ErrorType.Httpclient, e);
    } finally {

    }

}