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

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

Introduction

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

Prototype

public BufferedHttpEntity(HttpEntity httpEntity) throws IOException 

Source Link

Usage

From source file:com.pyj.http.BinaryHttpResponseHandler.java

@Override
void sendResponseMessage(HttpResponse response, int reqType) {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    byte[] responseBody = null;
    if (contentTypeHeaders.length != 1) {
        //malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(),
                "None, or more than one, Content-Type Header found!"), responseBody, reqType);
        return;/*from  w  w  w.  jav  a2s.  c o  m*/
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : mAllowedContentTypes) {
        if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
            foundAllowedContentType = true;
        }
    }
    if (!foundAllowedContentType) {
        //Content-Type not in allowed list, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"),
                responseBody, reqType);
        return;
    }
    try {
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
        }
        responseBody = EntityUtils.toByteArray(entity);
    } catch (IOException e) {
        sendFailureMessage(e, (byte[]) null, reqType);
    }

    if (status.getStatusCode() >= 300) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                responseBody, reqType);
    } else {
        sendSuccessMessage(status.getStatusCode(), responseBody, reqType);
    }
}

From source file:com.nimpres.android.web.APIContact.java

/**
 * Downloads the presentation dps file/*www  . jav a 2  s.c o  m*/
 * 
 * @param id
 * @param password
 * @return
 */
public static InputStream downloadPresentation(int presID, String presPass) {
    InputStream downloadedDps = null;
    String response = "";
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("pres_id", String.valueOf(presID)));
    params.add(new BasicNameValuePair("pres_password", presPass));
    HttpEntity resEntity = apiPostRequest(NimpresSettings.API_DOWNLOAD_PRESENTATION, params);
    try {
        BufferedHttpEntity buffEnt = new BufferedHttpEntity(resEntity); // Added for file download
        downloadedDps = buffEnt.getContent();
        response = new String(EntityUtils.toString(buffEnt).trim());
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (!response.equals(NimpresSettings.API_RESPONSE_NEGATIVE) && response != "") {
        Log.d("APIContact", "api download success");
        return downloadedDps;
    } else {
        Log.d("APIContact", "api download failed");
        return null;
    }
}

From source file:org.bibalex.gallery.storage.BAGStorage.java

protected static List<String> listChildrenApacheHttpd(String dirUrlStr, FileType childrenType,
        DefaultHttpClient httpclient) throws BAGException {
    ArrayList<String> result = new ArrayList<String>();

    HttpGet httpReq = new HttpGet(dirUrlStr);
    try {// ww w  .j  a  v  a2 s.c o m

        HttpResponse response = httpclient.execute(httpReq);

        if (response.getStatusLine().getStatusCode() / 100 != 2) {
            throw new BAGException("Connection error: " + response.getStatusLine().toString());
        }

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();

        // If the response does not enclose an entity, there is no need
        // to bother about connection release
        if ((entity != null)) {

            entity = new BufferedHttpEntity(entity);

            if (entity.getContentType().getValue().startsWith("text/html")) {
                SAXBuilder saxBuilder = new SAXBuilder();

                saxBuilder.setFeature("http://xml.org/sax/features/validation", false);
                saxBuilder.setFeature("http://xml.org/sax/features/namespaces", true);
                saxBuilder.setFeature("http://xml.org/sax/features/namespace-prefixes", true);

                String htmlresponse = EntityUtils.toString(entity);
                String xmlResponse = light_html2xml.Html2Xml(htmlresponse);

                Document doc = saxBuilder.build(new StringReader(xmlResponse));
                XPath hrefXP = XPath.newInstance("//a/@href");

                for (Object obj : hrefXP.selectNodes(doc)) {
                    Attribute attr = (Attribute) obj;
                    String name = attr.getValue();
                    if (name.startsWith("/")) {
                        // parent dir
                        continue;
                    } else if (name.endsWith("/")) {
                        if (childrenType.equals(FileType.FOLDER)
                                || childrenType.equals(FileType.FILE_OR_FOLDER)) {
                            result.add(name.substring(0, name.length() - 1));
                        }
                    } else {
                        if (childrenType.equals(FileType.FILE)
                                || childrenType.equals(FileType.FILE_OR_FOLDER)) {
                            result.add(name);
                        }
                    }
                }
            }
        }

        return result;

    } catch (IOException ex) {

        // In case of an IOException the connection will be released
        // back to the connection manager automatically
        throw new BAGException(ex);

    } catch (RuntimeException ex) {

        // In case of an unexpected exception you may want to abort
        // the HTTP request in order to shut down the underlying
        // connection and release it back to the connection manager.
        httpReq.abort();
        throw ex;

    } catch (JDOMException e) {
        throw new BAGException(e);
    } finally {
        // connection closing is left for the caller to reuse connections

    }

}

From source file:cn.kuwo.sing.phone4tv.commons.http.BinaryHttpResponseHandler.java

@Override
void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    byte[] responseBody = null;
    if (contentTypeHeaders.length != 1) {
        //malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(),
                "None, or more than one, Content-Type Header found!"), responseBody);
        return;//from w  ww  .  j a  v  a  2 s . c o m
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : mAllowedContentTypes) {
        if (anAllowedContentType.equals("*")
                || Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
            foundAllowedContentType = true;
        }
    }
    if (!foundAllowedContentType) {
        //Content-Type not in allowed list, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"),
                responseBody);
        return;
    }
    try {
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
        }
        responseBody = EntityUtils.toByteArray(entity);
    } catch (IOException e) {
        sendFailureMessage(e, (byte[]) null);
    }

    if (status.getStatusCode() >= 300) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                responseBody);
    } else {
        sendSuccessMessage(status.getStatusCode(), responseBody);
    }
}

From source file:com.example.wechatsample.library.http.BinaryHttpResponseHandler.java

void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    byte[] responseBody = null;
    if (contentTypeHeaders.length != 1) {
        // malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(),
                "None, or more than one, Content-Type Header found!"), responseBody);
        return;/*  w w w .  j  a va  2s  .com*/
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : mAllowedContentTypes) {
        if (anAllowedContentType.equals(contentTypeHeader.getValue())) {
            foundAllowedContentType = true;
        }
    }
    if (!foundAllowedContentType) {
        // Content-Type not in allowed list, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"),
                responseBody);
        return;
    }
    try {
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
        }
        responseBody = EntityUtils.toByteArray(entity);
    } catch (IOException e) {
        sendFailureMessage(e, (byte[]) null);
    }

    if (status.getStatusCode() >= 300) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                responseBody);
    } else {
        sendSuccessMessage(status.getStatusCode(), responseBody);
    }
}

From source file:com.heyzap.http.AsyncHttpResponseHandler.java

void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    String responseBody = null;/*from w  ww .j  av a 2 s.  co  m*/
    try {
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
            responseBody = EntityUtils.toString(entity, "UTF-8");
        }
    } catch (IOException e) {
        sendFailureMessage(e, null);
    }

    if (status.getStatusCode() >= 300) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                responseBody);
    } else {
        sendSuccessMessage(responseBody);
    }
}

From source file:com.fenglian.lib.base.sync.http.AsyncHttpResponseHandler.java

void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    String responseBody = null;/*from   ww w  . j  a  va  2  s  .  c o  m*/
    try {
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
        }
        responseBody = EntityUtils.toString(entity, "UTF-8");
    } catch (IOException e) {
        sendFailureMessage(e, null);
    }

    if (status.getStatusCode() >= 300) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                responseBody);
    } else {
        sendSuccessMessage(responseBody);
    }
}

From source file:utils.APIExporter.java

/**
 * This method get the API thumbnail and write in to the zip file
 * @param uuid API id of the API/* w ww.j  a va 2 s .co m*/
 * @param accessToken valide access token with view scope
 * @param APIFolderpath archive base path
 */
private static void exportAPIThumbnail(String uuid, String accessToken, String APIFolderpath) {
    ApiImportExportConfiguration config = ApiImportExportConfiguration.getInstance();
    try {
        //REST API call to get API thumbnail
        String url = config.getPublisherUrl() + "apis/" + uuid + "/thumbnail";
        CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate());
        HttpGet request = new HttpGet(url);
        request.setHeader(HttpHeaders.AUTHORIZATION,
                ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + accessToken);
        CloseableHttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();

        //assigning the response in to inputStream
        BufferedHttpEntity httpEntity = new BufferedHttpEntity(entity);
        InputStream imageStream = httpEntity.getContent();
        byte[] byteArray = IOUtils.toByteArray(imageStream);
        InputStream inputStream = new BufferedInputStream(new ByteArrayInputStream(byteArray));
        //getting the mime type of the input Stream
        String mimeType = URLConnection.guessContentTypeFromStream(inputStream);
        //getting file extension
        String extension = getThumbnailFileType(mimeType);
        OutputStream outputStream = null;
        if (extension != null) {
            //writing image in to the  archive
            try {
                outputStream = new FileOutputStream(APIFolderpath + File.separator + "icon." + extension);
                IOUtils.copy(httpEntity.getContent(), outputStream);
            } finally {
                IOUtils.closeQuietly(outputStream);
                IOUtils.closeQuietly(imageStream);
                IOUtils.closeQuietly(inputStream);
            }
        }
    } catch (IOException e) {
        log.error("Error occurred while exporting the API thumbnail");
    }

}

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/*from   ww w  .  j  a v a2s. 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:com.fastandroid.lib.http.AsyncHttpClient.BinaryHttpResponseHandler.java

@Override
protected void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    byte[] responseBody = null;
    if (contentTypeHeaders.length != 1) {
        // malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(),
                "None, or more than one, Content-Type Header found!"), responseBody);
        return;//from  w  ww.  ja  va  2  s  .  c om
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : mAllowedContentTypes) {
        if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
            foundAllowedContentType = true;
        }
    }
    if (!foundAllowedContentType) {
        // Content-Type not in allowed list, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"),
                responseBody);
        return;
    }
    try {
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
        }
        responseBody = EntityUtils.toByteArray(entity);
    } catch (IOException e) {
        sendFailureMessage(e, (byte[]) null);
    }

    if (status.getStatusCode() >= 300) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                responseBody);
    } else {
        sendSuccessMessage(status.getStatusCode(), responseBody);
    }
}