Example usage for org.apache.http.client HttpClient execute

List of usage examples for org.apache.http.client HttpClient execute

Introduction

In this page you can find the example usage for org.apache.http.client HttpClient execute.

Prototype

HttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException;

Source Link

Document

Executes HTTP request using the default context.

Usage

From source file:es.ugr.swad.swadroid.webservices.RestEasy.java

public static void doDelete(String url) throws ClientProtocolException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpDelete delete = new HttpDelete(url);
    delete.addHeader("accept", "application/json");
    httpclient.execute(delete);
}

From source file:com.android.dialer.omni.PlaceUtil.java

/**
 * Executes a get request and return byte array
 * @param url the API URL//from ww  w  .ja  v a  2  s .  c  o  m
 * @return the byte array containing the web page
 * @throws ClientProtocolException
 * @throws IOException
 */
public static byte[] getRequest(String url) throws ClientProtocolException, IOException {
    if (DEBUG)
        Log.d(TAG, "download: " + url);

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 15000);
    HttpConnectionParams.setSoTimeout(params, 15000);
    HttpClient client = new DefaultHttpClient(params);
    HttpGet request = new HttpGet(url);
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    byte[] htmlResultPage = null;
    if (entity != null) {
        htmlResultPage = EntityUtils.toByteArray(entity);
        entity.consumeContent();
    }

    return htmlResultPage;
}

From source file:com.gozap.chouti.service.HttpService.java

/**
 *
 * @param uri uri/*ww  w  .j a v  a  2s  .c  o  m*/
 * @return
 * @author saint
 * @date 2013-4-17
 */
public static Boolean post(String uri, UrlEncodedFormEntity entity) {
    HttpClient httpClient = HttpClientFactory.getInstance();
    HttpPost httpPost = new HttpPost(uri);
    httpPost.setEntity(entity);
    try {
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        String jsonStr = EntityUtils.toString(httpEntity);
        JSONObject json = JSON.parseObject(jsonStr);
        if (!json.getString("code").equals("99999")) {
            LOGGER.error("post uri:" + uri + ":" + entity + "error!" + "error msg: " + jsonStr);
        } else {
            return true;
        }
    } catch (ClientProtocolException e) {
        LOGGER.error("get" + uri + "error", e);
    } catch (IOException e) {
        LOGGER.error("get" + uri + "error", e);
    } finally {
        httpPost.releaseConnection();
    }

    return false;
}

From source file:org.liberty.android.fantastischmemo.downloader.DownloaderUtils.java

public static String downloadJSONString(String url) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);
    HttpResponse response;/*  w  ww.j ava2 s. com*/
    response = httpclient.execute(httpget);
    Log.i(TAG, "Response: " + response.getStatusLine().toString());
    HttpEntity entity = response.getEntity();

    if (entity == null) {
        throw new NullPointerException("Null entity error");
    }

    InputStream instream = entity.getContent();
    // Now convert stream to string 
    BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
    StringBuilder sb = new StringBuilder();
    String line = null;
    String result = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    result = sb.toString();

    return result;
}

From source file:com.splunk.shuttl.testutil.TUtilsMockito.java

private static HttpClient createHttpClientMockReturningHttpStatus(int httpStatus) {
    HttpClient httpClient = mock(HttpClient.class);
    StatusLine statusLine = mock(StatusLine.class);
    when(statusLine.getStatusCode()).thenReturn(httpStatus);
    try {/*www . j a v  a2s.  co m*/
        when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(new BasicHttpResponse(statusLine));
    } catch (Exception e) {
        TUtilsTestNG.failForException("Couldn't assign return value for execute", e);
    }
    return httpClient;
}

From source file:fr.julienvermet.bugdroid.util.NetworkUtils.java

public static NetworkResult readJson(String url) {
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    int statusCode = 0;
    try {//from w w  w  .ja va  2  s  . co m
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            reader.close();
        } else {
            Log.e(NetworkUtils.class.toString(), "Failed to download Json content");
        }

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

    }

    return new NetworkResult(statusCode, builder.toString());
}

From source file:com.meltmedia.cadmium.cli.WarInfoCommand.java

/**
 * Retrieves information about a deployed cadmium war.
 *  //from   w w  w.ja  v  a2  s .  co m
 * @param url The uri to a Cadmium deployer war.
 * @param warName The name of a deployed war.
 * @param token The Github API token used for authentication.
 * @return
 * @throws Exception
 */
public static WarInfo getDeployedWarInfo(String url, String warName, String token) throws Exception {
    HttpClient client = httpClient();

    HttpGet get = new HttpGet(url + "/system/deployment/details/" + warName);
    addAuthHeader(token, get);

    HttpResponse resp = client.execute(get);

    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        WarInfo info = new Gson().fromJson(EntityUtils.toString(resp.getEntity()), WarInfo.class);
        return info;
    }

    return null;
}

From source file:gov.nasa.ensemble.common.http.HttpUtils.java

public static <T> T execute(HttpClient client, HttpRequestBase request,
        HttpResponseHandlerWithResult<T> handler) throws Exception {
    T result = null;// w w w  .  ja  v  a  2  s.c  o m
    HttpResponse response = null;
    try {
        response = client.execute(request);
        if (handler != null) {
            result = handler.handleResponse(response);
        }
    } finally {
        HttpUtils.consume(request, response);
    }
    return result;
}

From source file:rawdata.ClientPlenarioRawData.java

/**
 * Metodo per eseguire una semplice query su Plenar.io
 * @throws IOException //from   w  ww  .ja  va 2  s . c  o m
 */
private static void executeQuery(String str_base_query, String outputFileName) throws IOException {

    //create the output file
    PrintWriter outputFile = new PrintWriter(outputFileName + ".csv");

    boolean completed = false; //the query is completed when all the pages are processed 
    int numPages = 0; //number of pages results are split
    int offSet = 0; //offset for the query, due to the limitation of Plenario (RESPONSE_LIMIT = 1000)
    int totalNumOfResults = 0; //total number of results, summed up on all the returned pages

    System.out.println("#Page:\t" + "#Instances");

    while (!completed) {

        //complete the query, by appending the right offset value
        String offset = "offset=" + offSet;
        String str_query = str_base_query + "&" + offset;

        //Submit the query to Plenario
        try {
            //create the http_query and submit it to Plenario
            HttpClient client = new DefaultHttpClient();
            HttpGet http_query = new HttpGet(str_query);
            HttpResponse response = client.execute(http_query);

            //has the query been correctly executed ?
            if (response.getStatusLine().getReasonPhrase().contains("Error")) { //Error
                System.out.println("Query Error!!!");
            } //if

            else { //OK, correctly executed
                //get the results in an array structure and update some variables
                String results = EntityUtils.toString(response.getEntity());
                String resultsArray[] = results.split("\n");
                int results_size = resultsArray.length;
                int numOfInstances = results_size - 1; //the first row is the attribute list 
                numPages++; //a new page of the query response
                totalNumOfResults += numOfInstances; //update the total number

                //the first row is the attribute list, so it must be printed 
                //only on the first page
                int firstRowToPrint = 0;
                if (numPages == 1)
                    firstRowToPrint = 0;
                else
                    firstRowToPrint = 1;

                //print the results page on the file and then flush
                for (int i = firstRowToPrint; i < resultsArray.length; i++)
                    outputFile.print(resultsArray[i]);

                outputFile.flush();

                System.out.println("Page " + numPages + ":\t" + numOfInstances + "(" + offset + ")");

                //if there are no other pages, stop; otherwise, 
                //update offset and re-submit the query
                if (resultsArray.length < OFFSET_STEP)
                    completed = true;
                else
                    offSet = offSet + OFFSET_STEP;

            } //else

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

    } //while

    System.out.println("TOTAL:\t" + totalNumOfResults);

}

From source file:fr.pingtimeout.ConnectionUtils.java

public static boolean pingServer(String serverHostname) {
    String pingUrlAsString = String.format("http://%s:8080/ping", serverHostname);
    Log.d(loggerName, "Pinging server " + pingUrlAsString);

    BufferedReader bufferedReader = null;
    try {//from w  ww.ja v  a  2 s  .c  o m
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(new URI(pingUrlAsString));

        HttpResponse response = client.execute(request);

        bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        while (bufferedReader.readLine() != null) {
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException ignored) {
            }
        }
    }

    return true;
}