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:tw.idv.gasolin.pycontw2012.util.BitmapUtils.java

/**
 * Only call this method from the main (UI) thread. The
 * {@link OnFetchCompleteListener} callback be invoked on the UI thread, but
 * image fetching will be done in an {@link AsyncTask}.
 * //from w w w .j a  v a  2 s.  c om
 * @param cookie
 *            An arbitrary object that will be passed to the callback.
 */
public static void fetchImage(final Context context, final String url,
        final BitmapFactory.Options decodeOptions, final Object cookie,
        final OnFetchCompleteListener callback) {
    new AsyncTask<String, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(String... params) {
            final String url = params[0];
            if (TextUtils.isEmpty(url)) {
                return null;
            }

            // First compute the cache key and cache file path for this URL
            File cacheFile = null;
            try {
                MessageDigest mDigest = MessageDigest.getInstance("SHA-1");
                mDigest.update(url.getBytes());
                final String cacheKey = bytesToHexString(mDigest.digest());
                if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                    cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Android"
                            + File.separator + "data" + File.separator + context.getPackageName()
                            + File.separator + "cache" + File.separator + "bitmap_" + cacheKey + ".tmp");
                }
            } catch (NoSuchAlgorithmException e) {
                // Oh well, SHA-1 not available (weird), don't cache
                // bitmaps.
            }

            if (cacheFile != null && cacheFile.exists()) {
                Bitmap cachedBitmap = BitmapFactory.decodeFile(cacheFile.toString(), decodeOptions);
                if (cachedBitmap != null) {
                    return cachedBitmap;
                }
            }

            try {
                // TODO: check for HTTP caching headers
                final HttpClient httpClient = SyncService.getHttpClient(context.getApplicationContext());
                final HttpResponse resp = httpClient.execute(new HttpGet(url));
                final HttpEntity entity = resp.getEntity();

                final int statusCode = resp.getStatusLine().getStatusCode();
                if (statusCode != HttpStatus.SC_OK || entity == null) {
                    return null;
                }

                final byte[] respBytes = EntityUtils.toByteArray(entity);

                // Write response bytes to cache.
                if (cacheFile != null) {
                    try {
                        cacheFile.getParentFile().mkdirs();
                        cacheFile.createNewFile();
                        FileOutputStream fos = new FileOutputStream(cacheFile);
                        fos.write(respBytes);
                        fos.close();
                    } catch (FileNotFoundException e) {
                        Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e);
                    } catch (IOException e) {
                        Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e);
                    }
                }

                // Decode the bytes and return the bitmap.
                return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, decodeOptions);
            } catch (Exception e) {
                Log.w(TAG, "Problem while loading image: " + e.toString(), e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            callback.onFetchComplete(cookie, result);
        }
    }.execute(url);
}

From source file:com.navnorth.learningregistry.LRClient.java

public static String executeHttpGet(String url) throws Exception {
    BufferedReader in = null;//  w ww.  j ava2  s .com
    try {
        URI uri = new URI(url);
        HttpClient client = getHttpClient(uri.getScheme());
        HttpGet request = new HttpGet(uri);

        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();
        String result = sb.toString();
        return result;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.navnorth.learningregistry.LRClient.java

public static String executeJsonGet(String url) throws Exception {
    BufferedReader in = null;/*from w ww .j  a  v  a2 s . c  o  m*/
    try {
        URI uri = new URI(url);
        HttpClient client = getHttpClient(uri.getScheme());
        HttpGet request = new HttpGet(uri);

        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();
        String result = sb.toString();
        return result;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:co.cask.tigon.test.SQLFlowTestBase.java

/**
 * This function returns the output data packets generated by the given flow
 * @param outputClass {@link java.lang.Class} of the output type object
 * @param <T> The output type object class
 * @return An instance of the output type object
 * @throws IOException/* w w  w.  j  a v a2  s.  c  o m*/
 */
public static <T> T getDataPacket(Class<T> outputClass) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(serviceURL + "/poll");
    HttpResponse response = httpClient.execute(httpGet);
    if (response.getStatusLine().getStatusCode() != 200) {
        return null;
    }
    String serializedDataPacket = EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
    return GSON.fromJson(serializedDataPacket, outputClass);
}

From source file:com.android.exchange.EasResponse.java

public static EasResponse fromHttpRequest(EmailClientConnectionManager connManager, HttpClient client,
        HttpUriRequest request) throws IOException {
    final long reqTime = System.currentTimeMillis();
    final HttpResponse response = client.execute(request);
    return new EasResponse(response, connManager, reqTime);
}

From source file:com.mashape.unirest.android.http.HttpClientHelper.java

public static <T> HttpResponse<T> request(HttpRequest request, Class<T> responseClass) throws UnirestException {
    HttpRequestBase requestObj = prepareRequest(request, false);
    HttpClient client = ClientFactory.getHttpClient(); // The
    // DefaultHttpClient
    // is thread-safe

    org.apache.http.HttpResponse response;
    try {/*from w w  w .j a v a2 s  .  co  m*/
        response = client.execute(requestObj);
        HttpResponse<T> httpResponse = new HttpResponse<T>(response, responseClass);
        return httpResponse;
    } catch (Exception e) {
        throw new UnirestException(e);
    }
}

From source file:it410.gmu.edu.OrderingServiceClient.java

public static void addCustomerJSON(Customer customer) throws IOException {

    Gson gson = new Gson();
    String customerString = gson.toJson(customer);
    System.out.println("Customer JSON = " + customerString);

    HttpClient client = new DefaultHttpClient();

    HttpPost post = new HttpPost("http://localhost:8080/BookstoreRestService/generic/addOrderJSON");
    post.setHeader("Content-Type", "application/json");
    StringEntity entity = new StringEntity(customerString);
    post.setEntity(entity);//from  w w w. jav a2  s .  c om
    HttpResponse response = client.execute(post);

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line = "";
    while ((line = rd.readLine()) != null) {
        System.out.println(line);
    }

}

From source file:com.foobnix.api.vkontakte.VkOld.java

public static List<VkAudio> searchAll(String text, Context context) throws VKAuthorizationException {

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("q", text));
    params.add(new BasicNameValuePair("count", "100"));
    params.add(new BasicNameValuePair("access_token", Pref.getStr(context, Pref.VKONTAKTE_TOKEN)));

    String paramsList = URLEncodedUtils.format(params, "UTF-8");
    HttpGet request = new HttpGet(API_URL + "audio.search?" + paramsList);

    HttpClient client = new DefaultHttpClient();
    HttpResponse response;//  ww w.  ja va  2s. c  om
    List<VkAudio> result = null;
    try {
        response = client.execute(request);

        HttpEntity entity = response.getEntity();
        String jString = EntityUtils.toString(entity);

        if (jString.contains("error_code")) {
            throw new VKAuthorizationException("VK connection Erorr");
        }

        LOG.d(jString);

        result = JSONHelper.parseVKSongs(jString);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    return result;

}

From source file:edu.umn.msi.tropix.transfer.http.client.HttpTransferClients.java

static HttpResponse execute(final HttpClient client, final HttpUriRequest request) {
    try {/*from w  w  w  . j ava  2  s. com*/
        final HttpResponse response = client.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            throw new RuntimeException("Transfer failed - server returned response code " + statusCode);
        }
        return response;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.meshpoint.anode.util.ModuleUtils.java

public static File getResource(URI httpUri, String filename) throws IOException {
    /* download */
    HttpClient http = new DefaultHttpClient();
    HttpGet request = new HttpGet();
    request.setURI(httpUri);/*from   w ww  .  j av a 2  s  .c  om*/
    HttpEntity entity = http.execute(request).getEntity();
    InputStream in = entity.getContent();
    File destination = new File(resourceDir, filename);
    FileOutputStream out = new FileOutputStream(destination);
    byte[] buf = new byte[1024];
    int read;
    while ((read = in.read(buf)) != -1) {
        out.write(buf, 0, read);
    }
    in.close();
    out.flush();
    out.close();
    return destination;
}