Example usage for org.apache.http.entity BufferedHttpEntity getContent

List of usage examples for org.apache.http.entity BufferedHttpEntity getContent

Introduction

In this page you can find the example usage for org.apache.http.entity BufferedHttpEntity getContent.

Prototype

public InputStream getContent() throws IOException 

Source Link

Usage

From source file:org.service.TaskGetEdifice.java

private Boolean getRestFul() {

    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(HTTP_RESTFUL);

    Boolean strResultado = true;//from w w w.j  a  v a2 s  .com
    try {
        //ejecuta
        HttpResponse response = httpclient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        BufferedHttpEntity buffer = new BufferedHttpEntity(entity);
        InputStream iStream = buffer.getContent();

        String aux = "";

        BufferedReader r = new BufferedReader(new InputStreamReader(iStream));
        StringBuilder total = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
            aux += line;
        }
        JSONObject jsonObject = new JSONObject(aux);
        JSONArray array = jsonObject.getJSONArray("edifice");
        edifices = new Edifice[array.length()];
        // Recorremos el array con los elementos cities
        for (int i = 0; i < array.length(); i++) {
            JSONObject row = array.getJSONObject(i);
            String idEdifice = row.getString("idEdifice");
            String NameEdifice;
            NameEdifice = row.getString("NameEdifice");
            edifices[i] = new Edifice(idEdifice, NameEdifice);
        }
        return strResultado;

    } catch (ClientProtocolException e) {
        strResultado = false;
        e.printStackTrace();
    } catch (IOException e) {
        strResultado = false;
        e.printStackTrace();
    } catch (JSONException e) {
        strResultado = false;
        e.printStackTrace();
    }
    return strResultado;
}

From source file:com.sytecso.jbpm.client.rs.JbpmRestTemplate.java

private byte[] requestImage(String url) throws Exception {
    log.info("--- IMAGE");
    HttpGet httpGet = new HttpGet(url);
    /*if(!this.SESSION_ID.equals("")){
    httpGet.setHeader("Cookie", "JSESSIONID="+SESSION_ID); 
    }*///from  ww  w  .j a v a  2 s  . com
    HttpResponse response = httpClient.execute(httpGet);
    log.info("image size: " + response.getEntity().getContentLength());
    BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(response.getEntity());
    return IOUtils.toByteArray(bufferedHttpEntity.getContent());
}

From source file:com.mobilevangelist.glass.helloworld.GetTheWeatherActivity.java

private Bitmap loadImageFromURL(String getURL) {

    try {/*from w  w w  . ja  v a 2s  .c  o m*/
        URL url = new URL(getURL);

        HttpGet httpRequest = null;
        httpRequest = new HttpGet(url.toURI());
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
        HttpEntity entity = response.getEntity();
        BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
        InputStream input = b_entity.getContent();
        Bitmap bitmap = BitmapFactory.decodeStream(input);
        return bitmap;
    } catch (Exception ex) {

        Toast t2 = Toast.makeText(getApplicationContext(), "Image Loading Failed", Toast.LENGTH_LONG);
        t2.setGravity(Gravity.CENTER, 0, 0);
        t2.show();
        return null;
    }
}

From source file:com.othermedia.asyncimage.AsyncImageDownloader.java

@Override
public void run() {
    if (parentImageCache == null)
        return;/*from w  w  w. j  a v  a  2 s .  c om*/

    // The downloader runs until the queue is empty or the cache is disconnected
    while (parentImageCache != null && parentImageCache.downloadQueue.size() > 0) {

        AsyncImageTask currentTask = parentImageCache.downloadQueue.remove(0); // Pop first task in (FIFO)

        try {

            // -- Check and retrieve file cache
            String hashedPath = null;
            try {
                if (parentImageCache.isFileCacheEnabled()) {
                    hashedPath = parentImageCache.hashString(currentTask.getImageURL()) + ".png";
                    if (parentImageCache.hasInFileCache(hashedPath)) {
                        parentImageCache.fileCacheRetrieve(hashedPath, currentTask.getImageURL());
                    }
                }
            } catch (Exception e) {
                Log.e(DebugTag, "Exception on retrieving from file cache: " + e + ": " + e.getMessage());
            }

            // - Check cache, if the image got retrieved by an earlier request or from file cache
            if (parentImageCache.hasCached(currentTask.getImageURL())) {
                parentImageCache.updateTargetFromHandler(currentTask.getTargetImageView(),
                        currentTask.getImageURL());
            } else {
                // ...Else download image:

                int tries = 3; // Allowed download Tries

                while (tries > 0) {
                    tries--; // In case of a short network drop or other random connection error.

                    try {

                        // -- Create HTTP Request
                        URL requestUrl = new URL(currentTask.getImageURL());
                        HttpGet httpRequest = new HttpGet(requestUrl.toURI());
                        HttpClient httpClient = new DefaultHttpClient();
                        HttpResponse httpResponse = (HttpResponse) httpClient.execute(httpRequest);

                        // -- Process Bitmap Download
                        BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(httpResponse.getEntity());
                        InputStream inputStream = bufferedEntity.getContent();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        BitmapDrawable drawable = new BitmapDrawable(bitmap);
                        parentImageCache.cacheImage(currentTask.getImageURL(), drawable); // - cache downloaded bitmap, then update ImageView:
                        parentImageCache.updateTargetFromHandler(currentTask.getTargetImageView(),
                                currentTask.getImageURL());

                        tries = 0; // Release tries.
                        inputStream.close();

                        // -- Cache Drawable as file, if enabled
                        if (parentImageCache.isFileCacheEnabled()) {
                            try {
                                if (hashedPath != null) {
                                    File outputFile = new File(parentImageCache.getCacheDir(), hashedPath);
                                    FileOutputStream outputStream = new FileOutputStream(outputFile);
                                    bitmap.compress(Bitmap.CompressFormat.PNG, 90, outputStream);
                                }
                            } catch (Exception e) {
                                Log.e(DebugTag,
                                        "Exception on file caching process: " + e + ": " + e.getMessage());
                            }
                        } // -- End file caching.

                    } catch (Exception e) {
                        Log.e(DebugTag, "Exception on download process: " + e + ": " + e.getMessage());
                        try {
                            Thread.sleep(250);
                        } catch (InterruptedException ei) {
                        }
                    }
                }
            }

        } catch (Exception e) {
            Log.e(DebugTag, "Exception on current AsyncImageTask: " + e + ": " + e.getMessage());
        }

    }

    parentImageCache.downloaderFinished(); // Release thread reference from cache

}

From source file:com.apkits.android.widget.WebImageView.java

/**
 * </br><b>description :</b>???
 * </br><b>time :</b>      2012-8-4 ?4:03:19
 * @param url/*w  w w .j  a va 2 s. c o  m*/
 */
public void fetchFromUrl(final String url) {
    if (!CommonRegex.matcherRegex("[\\w\\p{P}]*\\.[jpngifJPNGIF]{3,4}", url)) {
        if (mDefaultImageRes != 0)
            setImageResource(mDefaultImageRes);
        WebImageView.this.invalidate();
        return;
    }
    final String tempFile = HashEncrypt.encode(CryptType.SHA1, url);
    //?
    if (mContext.getFileStreamPath(tempFile).exists()) {
        Message msg = new Message();
        msg.what = State.Success;
        msg.obj = tempFile;
        mDownloadCallback.sendMessage(msg);
    } else {
        //
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg = new Message();
                msg.what = State.Success;
                try {
                    HttpGet httpRequest = new HttpGet(url);
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
                    HttpEntity entity = response.getEntity();
                    BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(entity);
                    InputStream is = bufferedHttpEntity.getContent();
                    FileOutputStream os = mContext.openFileOutput(tempFile, Context.MODE_PRIVATE);
                    byte[] cache = new byte[1 * 1024];
                    for (int len = 0; (len = is.read(cache)) != -1;) {
                        os.write(cache, 0, len);
                    }
                    os.close();
                    is.close();
                    msg.obj = tempFile;
                } catch (IOException e) {
                    msg.obj = e.getMessage();
                    msg.what = State.Error;
                    e.printStackTrace();
                } finally {
                    mDownloadCallback.sendMessage(msg);
                }
            }
        }).start();
    }
}

From source file:org.example.camera.List14.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    URL myFileUrl = null;//from w w  w. j a va  2  s.co  m
    try {
        URL url = new URL("http://wheelspotting.com/recent.json");
        URLConnection tc = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));

        String line;
        while ((line = in.readLine()) != null) {
            JSONArray ja = new JSONArray(line);
            Log.i("jsondeal", ja.getString(0));

            for (int i = 0; i < ja.length(); i++) {
                JSONObject jo = (JSONObject) ja.get(i);
                try {
                    myFileUrl = new URL(jo.getString("medium_image"));
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                HttpGet httpRequest = null;
                try {
                    httpRequest = new HttpGet(myFileUrl.toURI());
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
                HttpEntity entity = response.getEntity();
                BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
                InputStream instream = bufHttpEntity.getContent();
                Bitmap bmImg = BitmapFactory.decodeStream(instream);
                listPics.add(bmImg);
                listTitles.add(jo.getString("title"));
                listLargeUrls.add(jo.getString("large_image"));
            }
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    setListAdapter(new EfficientAdapter(this));
}

From source file:de.mojadev.ohmmarks.virtuohm.VirtuOhmHTTPHandler.java

private String getResponseText(HttpResponse response) throws IllegalStateException, IOException {

    BufferedHttpEntity responseEntity = new BufferedHttpEntity(response.getEntity());

    int contentLength = (int) responseEntity.getContentLength();
    InputStream stream = responseEntity.getContent();

    byte buffer[] = new byte[contentLength];
    stream.read(buffer, 0, contentLength);

    return new String(buffer);

}

From source file:com.guster.brandon.library.webservice.RequestHandler.java

/**
 * Main method of sending HTTP Request to the server
 * @param rq Apache HTTP Base Request/*w w  w .j a  va  2 s  .c o  m*/
 * @return Response, if no response from the server or no internet connection,
 *          this object will return null
 * @throws IOException
 */
private Response send(HttpRequestBase rq) throws IOException {
    //Log.d("NISSAN", "WebService: Connecting to url... " + rq.getURI());
    HttpResponse httpResponse = httpClient.execute(rq);
    HttpEntity entity = httpResponse.getEntity();
    BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
    InputStream inputStream = bufHttpEntity.getContent();
    InputStream rawInputStream = bufHttpEntity.getContent();

    // variables to be put into Response
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    String statusDesc = httpResponse.getStatusLine().getReasonPhrase();
    long contentLength = entity.getContentLength();

    // onPrepare the response
    Response responseObject = new Response();
    responseObject.setStatusCode(statusCode);
    responseObject.setStatusDesc(statusDesc);
    responseObject.setContentLength(contentLength);
    responseObject.setRawResponse(rawInputStream);
    responseObject.setContentEncoding(entity.getContentEncoding());
    responseObject.setContentType(entity.getContentType());
    responseObject.setUrl(rq.getURI().toString());

    return responseObject;
}

From source file:com.twotoasters.android.horizontalimagescroller.io.ImageCacheManager.java

protected InputStream fetch(ImageUrlRequest imageUrlRequest) throws MalformedURLException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    ImageToLoadUrl imageToLoadUrl = imageUrlRequest.getImageToLoadUrl();
    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(imageToLoadUrl.getUsername(), imageToLoadUrl.getPassword()));
    HttpResponse response = httpClient.execute(new HttpGet(imageToLoadUrl.getUrl()));
    int statusCode = response.getStatusLine().getStatusCode();
    String reason = response.getStatusLine().getReasonPhrase();
    if (statusCode > 299) {
        throw new HttpResponseException(statusCode, reason);
    }//from  www  .j  ava2  s.com
    BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity());
    return entity.getContent();
}

From source file:fr.mael.jiwigo.dao.impl.ImageDaoImpl.java

public void addSimple(File file, Integer category, String title, Integer level) throws JiwigoException {
    HttpPost httpMethod = new HttpPost(((SessionManagerImpl) sessionManager).getUrl());

    //   nameValuePairs.add(new BasicNameValuePair("method", "pwg.images.addSimple"));
    //   for (int i = 0; i < parametres.length; i += 2) {
    //       nameValuePairs.add(new BasicNameValuePair(parametres[i], parametres[i + 1]));
    //   }//from  w  w w  .  j  a  v  a2s .  c o m
    //   method.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    if (file != null) {
        MultipartEntity multipartEntity = new MultipartEntity();

        //      String string = nameValuePairs.toString();
        // dirty fix to remove the enclosing entity{}
        //      String substring = string.substring(string.indexOf("{"),
        //            string.lastIndexOf("}") + 1);
        try {
            multipartEntity.addPart("method", new StringBody(MethodsEnum.ADD_SIMPLE.getLabel()));
            multipartEntity.addPart("category", new StringBody(category.toString()));
            multipartEntity.addPart("name", new StringBody(title));
            if (level != null) {
                multipartEntity.addPart("level", new StringBody(level.toString()));
            }
        } catch (UnsupportedEncodingException e) {
            throw new JiwigoException(e);
        }

        //      StringBody contentBody = new StringBody(substring,
        //            Charset.forName("UTF-8"));
        //      multipartEntity.addPart("entity", contentBody);
        FileBody fileBody = new FileBody(file);
        multipartEntity.addPart("image", fileBody);
        ((HttpPost) httpMethod).setEntity(multipartEntity);
    }

    HttpResponse response;
    StringBuilder sb = new StringBuilder();
    try {
        response = ((SessionManagerImpl) sessionManager).getClient().execute(httpMethod);

        int responseStatusCode = response.getStatusLine().getStatusCode();

        switch (responseStatusCode) {
        case HttpURLConnection.HTTP_CREATED:
            break;
        case HttpURLConnection.HTTP_OK:
            break;
        case HttpURLConnection.HTTP_BAD_REQUEST:
            throw new JiwigoException("status code was : " + responseStatusCode);
        case HttpURLConnection.HTTP_FORBIDDEN:
            throw new JiwigoException("status code was : " + responseStatusCode);
        case HttpURLConnection.HTTP_NOT_FOUND:
            throw new JiwigoException("status code was : " + responseStatusCode);
        default:
            throw new JiwigoException("status code was : " + responseStatusCode);
        }

        HttpEntity resultEntity = response.getEntity();
        BufferedHttpEntity responseEntity = new BufferedHttpEntity(resultEntity);

        BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
        String line;

        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
        } finally {
            reader.close();
        }
    } catch (ClientProtocolException e) {
        throw new JiwigoException(e);
    } catch (IOException e) {
        throw new JiwigoException(e);
    }
    String stringResult = sb.toString();

}