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:com.huguesjohnson.retroleague.util.HttpFetch.java

public static InputStream fetch(String address, int timeout) throws MalformedURLException, IOException {
    HttpGet httpRequest = new HttpGet(URI.create(address));
    HttpClient httpclient = new DefaultHttpClient();
    final HttpParams httpParameters = httpclient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeout);
    HttpConnectionParams.setSoTimeout(httpParameters, timeout);
    HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
    HttpEntity entity = response.getEntity();
    BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
    InputStream instream = bufHttpEntity.getContent();
    return (instream);
}

From source file:in.goahead.apps.util.URLUtils.java

public static String getURLFileName(String url) throws MalformedURLException, IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);

    HttpResponse httpResponse = httpClient.execute(httpGet);
    //      Logger.debug(java.util.Arrays.toString(httpResponse.getAllHeaders()));
    //      Header[] fileNameHeaders = httpResponse.getAllHeaders();
    //      for(Header h : fileNameHeaders) {
    //         Logger.debug(h.getName() + " :::: " + h.getValue());
    //      }/* w  w  w  .j a v a  2 s  .c  o  m*/
    Header fileNameHeaders = httpResponse.getHeaders("Content-Disposition")[0];
    String fileName = fileNameHeaders.getValue().replaceAll(".*filename=", "");

    return fileName;
}

From source file:jp.co.conit.sss.sn.ex1.util.SNApiUtil.java

private static SNServerResult post(String url, List<NameValuePair> postData, SNServerResult result) {

    try {//ww w. j  av a  2 s .  c  om
        HttpClient httpCli = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        post.setEntity(new UrlEncodedFormEntity(postData, "utf-8"));

        HttpResponse response = httpCli.execute(post);
        int status = response.getStatusLine().getStatusCode();
        result.mHttpStatus = status;

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String responseBodyText = EntityUtils.toString(entity);
            entity.consumeContent();
            httpCli.getConnectionManager().shutdown();
            result.mResponseString = responseBodyText;
        }

    } catch (Exception e) {
        result.mCauseException = e;
        e.printStackTrace();
    }
    return result;
}

From source file:com.plnyyanks.frcnotebook.datafeed.GET_Request.java

public static String getWebData(String url, boolean tbaheader) {

    InputStream is = null;/*ww w  . jav  a 2  s .c  om*/
    String result = "";

    // HTTP
    try {
        HttpClient httpclient = new DefaultHttpClient(); // for port 80 requests!
        HttpGet httpget = new HttpGet(url);
        if (tbaheader)
            httpget.addHeader(Constants.TBA_HEADER, Constants.TBA_HEADER_TEXT);
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    } catch (Exception e) {
        Log.e(Constants.LOG_TAG, e.toString());
        return null;
    }

    // Read response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
        Log.e(Constants.LOG_TAG, e.toString());
        return null;
    }

    return result;

}

From source file:com.welocalize.dispatcherMW.client.Main.java

public static void downloadJob(String p_jobId, String p_securityCode) {
    File parent = new File("target/" + p_jobId);
    String url = getFunctinURL(TYPE_DOWNLOAD, p_securityCode, p_jobId);
    HttpClient httpClient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet(url);
    try {//from w  w w  .ja  va  2s .  co m
        HttpResponse response = httpClient.execute(httpget);
        String fileName = response.getHeaders("Content-Disposition")[0].getValue().split("\"")[1];
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            if (!parent.exists())
                parent.mkdirs();
            FileOutputStream fos = new FileOutputStream(parent.getAbsolutePath() + "/" + fileName);
            entity.writeTo(fos);
            fos.close();
        }

        System.out.println("Download file:" + parent.getAbsolutePath() + "/" + fileName);
    } catch (Exception e) {
        System.out.println("Download XLF file error:\n" + e);
    } finally {
        httpget.releaseConnection();
    }
}

From source file:com.goliathonline.android.kegbot.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}.
 *
 * @param cookie An arbitrary object that will be passed to the callback.
 *///  www . ja  v  a2 s.  c  o  m
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.meltmedia.cadmium.cli.UndeployCommand.java

/**
 * Retrieves a list of Cadmium wars that are deployed.
 *  //from w  w  w  .  j a v  a  2  s .c om
 * @param url The uri to a Cadmium deployer war.
 * @param token The Github API token used for authentication.
 * @return
 * @throws Exception
 */
public static List<String> getDeployed(String url, String token) throws Exception {
    List<String> deployed = new ArrayList<String>();
    HttpClient client = httpClient();

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

    HttpResponse resp = client.execute(get);

    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        List<String> respList = new Gson().fromJson(EntityUtils.toString(resp.getEntity()),
                new TypeToken<List<String>>() {
                }.getType());

        if (respList != null) {
            deployed.addAll(respList);
        }
    }

    return deployed;
}

From source file:org.energyos.espi.datacustodian.console.ImportUsagePoint.java

public static void upload(String filename, String url, HttpClient client) throws IOException {
    HttpPost post = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    File file = new File(filename);
    entity.addPart("file", new FileBody(((File) file), "application/rss+xml"));

    post.setEntity(entity);//w ww  .  j  a  v  a  2s .  com

    client.execute(post);
}

From source file:com.wms.opensource.images3android.images3.ImageS3Service.java

public static boolean deleteImage(String baseUrl, String imagePlantId, String imageId) {
    HttpClient client = getClient();
    String url = baseUrl + imagePlantId + "/images/" + imageId;
    HttpDelete httpDelete = new HttpDelete(url);
    HttpResponse response;/*w  w w .  j ava 2s  .c o m*/
    try {
        response = client.execute(httpDelete);
        int code = response.getStatusLine().getStatusCode();
        if (code == 204) {
            return true;
        }
    } catch (ClientProtocolException e) {

    } catch (IOException e) {

    }
    return false;
}

From source file:jp.co.conit.sss.sn.ex2.util.SNApiUtil.java

/**
 * GET????<br>//w w w  .  jav  a 2s.c  o  m
 * Exception????????<br>
 * HTTP?SUCCESS???????SNServerResult???????
 * 
 * @param url
 * @param result
 * @return
 */
private static SNServerResult get(String url, SNServerResult result) {

    try {
        Log.d("SN", "GET url:" + url);
        HttpClient httpCli = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        HttpResponse response = httpCli.execute(get);
        int status = response.getStatusLine().getStatusCode();
        result.mHttpStatus = status;

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String responseBodyText = EntityUtils.toString(entity);
            entity.consumeContent();
            httpCli.getConnectionManager().shutdown();
            result.mResponseString = responseBodyText;
            Log.d("SN", "GET response:" + responseBodyText);
        }
    } catch (Exception e) {
        result.mCauseException = e;
        e.printStackTrace();
    }
    return result;
}