Example usage for org.apache.http.util EntityUtils getContentCharSet

List of usage examples for org.apache.http.util EntityUtils getContentCharSet

Introduction

In this page you can find the example usage for org.apache.http.util EntityUtils getContentCharSet.

Prototype

@Deprecated
    public static String getContentCharSet(HttpEntity httpEntity) throws ParseException 

Source Link

Usage

From source file:com.nesscomputing.httpclient.factory.httpclient4.InternalResponse.java

@Override
public String getCharset() {
    if (httpResponse != null) {
        final HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            return EntityUtils.getContentCharSet(entity);
        }/*from   w ww.j  a  v  a  2 s  . c o  m*/
    }
    return null;
}

From source file:org.eclipse.mylyn.commons.repositories.http.core.CommonHttpResponse.java

public String getResponseCharSet() {
    return EntityUtils.getContentCharSet(response.getEntity());
}

From source file:de.jetwick.snacktory.HttpPageReader.java

/** {@inheritDoc}*/
@SuppressWarnings("deprecation")
@Override//from  ww w  . j a v  a2  s  .  c  o m
public String readPage(String url) throws PageReadException {
    LOG.info("Reading " + url);
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 10000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
    HttpContext localContext = new BasicHttpContext();
    HttpGet get = new HttpGet(url);
    InputStream response = null;
    HttpResponse httpResponse = null;
    try {
        try {
            httpResponse = httpclient.execute(get, localContext);
            int resp = httpResponse.getStatusLine().getStatusCode();
            if (HttpStatus.SC_OK != resp) {
                LOG.error("Download failed of " + url + " status " + resp + " "
                        + httpResponse.getStatusLine().getReasonPhrase());
                return null;
            }
            String respCharset = EntityUtils.getContentCharSet(httpResponse.getEntity());

            return readContent(httpResponse.getEntity().getContent(), respCharset);
        } finally {
            if (response != null) {
                response.close();
            }
            if (httpResponse != null && httpResponse.getEntity() != null) {
                httpResponse.getEntity().consumeContent();
            }

        }
    } catch (IOException e) {
        LOG.error("Download failed of " + url, e);
        throw new PageReadException("Failed to read " + url, e);
    }
}

From source file:de.jetwick.snacktory.HijackableHttpPageReader.java

/** {@inheritDoc}*/
@SuppressWarnings("deprecation")
@Override//from w w w .j a v  a 2 s . c om
public String readPage(String url) throws PageReadException {
    if (url.equals(this.url) && StringUtils.isNotEmpty(pageHtml)) {
        LOG.info("Use already fetched content of " + url);

        return pageHtml;
    } else {
        LOG.info("Reading " + url);
        this.url = url;
        this.pageHtml = null;

        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT) 
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 10000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);

        HttpContext localContext = new BasicHttpContext();
        HttpGet get = new HttpGet(url);
        get.setHeader("User-Agent", userAgent);
        InputStream response = null;
        HttpResponse httpResponse = null;
        try {
            try {
                httpResponse = httpclient.execute(get, localContext);
                int resp = httpResponse.getStatusLine().getStatusCode();
                if (HttpStatus.SC_OK != resp) {
                    LOG.error("Download failed of " + url + " status " + resp + " "
                            + httpResponse.getStatusLine().getReasonPhrase());
                    return null;
                }
                String respCharset = EntityUtils.getContentCharSet(httpResponse.getEntity());

                pageHtml = readContent(httpResponse.getEntity().getContent(), respCharset);
                return pageHtml;
            } finally {
                if (response != null) {
                    response.close();
                }
                if (httpResponse != null && httpResponse.getEntity() != null) {
                    httpResponse.getEntity().consumeContent();
                }

            }
        } catch (IOException e) {
            LOG.error("Download failed of " + url, e);
            throw new PageReadException("Failed to read " + url, e);
        }
    }
}

From source file:net.opentracker.android.OTSend.java

/**
 * getResponseBody function gives out the HTTP POST data from the given
 * httpResponse output: data from the http as string input : httpEntity type
 * //from w w w  .  j av  a2s .c o  m
 * based on:
 * http://thinkandroid.wordpress.com/2009/12/30/getting-response-body
 * -of-httpresponse/
 */
private static String getResponseBody(final HttpEntity entity) throws IOException, ParseException {
    LogWrapper.v(TAG, "getResponseBody(final HttpEntity entity)");

    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }
    InputStream instream = entity.getContent();
    if (instream == null) {
        return "";
    }
    if (entity.getContentLength() > Integer.MAX_VALUE) {
        throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
    }
    String charset = EntityUtils.getContentCharSet(entity);
    if (charset == null) {
        charset = HTTP.DEFAULT_CONTENT_CHARSET;
    }
    Reader reader = new InputStreamReader(instream, charset);
    StringBuilder buffer = new StringBuilder();
    try {
        char[] tmp = new char[1024];
        int l;
        while ((l = reader.read(tmp)) != -1) {
            buffer.append(tmp, 0, l);
        }
    } finally {
        reader.close();
    }
    return buffer.toString();
}

From source file:org.tellervo.desktop.wsi.JaxbResponseHandler.java

public T toDocument(final HttpEntity entity, final String defaultCharset) throws IOException, ParseException {
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }/*from   w  w w  .  j  a v a 2s.  c  o  m*/

    InputStream instream = entity.getContent();
    if (instream == null) {
        return null;
    }

    String charset = EntityUtils.getContentCharSet(entity);
    if (charset == null) {
        charset = defaultCharset;
    }
    if (charset == null) {
        charset = HTTP.DEFAULT_CONTENT_CHARSET;
    }

    /**
     * Methodology
     * 1) Save XML to disk temporarily (it can be big, 
     *       we might want to look at it as a raw file)
     * 2) If we can't write to disk, throw IOException
     * 3) Try to parse
     * 4) Throw error with the raw document (it's malformed XML)
     */

    File tempFile = null;
    OutputStreamWriter fileOut = null;
    boolean usefulFile = false; // preserve this file outside this local context?

    try {
        tempFile = File.createTempFile("tellervo", ".xml");
        fileOut = new OutputStreamWriter(new FileOutputStream(tempFile, false), charset);

        // ok, dump the webservice xml to a file
        BufferedReader webIn = new BufferedReader(new InputStreamReader(instream, charset));

        char indata[] = new char[8192];
        int inlen;

        // write the file out
        while ((inlen = webIn.read(indata)) >= 0)
            fileOut.write(indata, 0, inlen);

        fileOut.close();
    } catch (IOException ioe) {
        // File I/O failed (?!) Clean up and re-throw the IOE.
        if (fileOut != null)
            fileOut.close();
        if (tempFile != null)
            tempFile.delete();

        throw ioe;
    }

    try {
        Unmarshaller um = context.createUnmarshaller();
        ValidationEventCollector vec = new ValidationEventCollector();

        // validate against this schema
        um.setSchema(validateSchema);

        // collect events instead of throwing exceptions
        um.setEventHandler(vec);

        // do the magic!
        Object ret = um.unmarshal(tempFile);

        // typesafe way of checking if this is the right type!
        return returnClass.cast(ret);
    } catch (UnmarshalException ume) {
        usefulFile = true;
        throw new ResponseProcessingException(ume, tempFile);

    } catch (JAXBException jaxbe) {
        usefulFile = true;
        throw new ResponseProcessingException(jaxbe, tempFile);

    } catch (ClassCastException cce) {
        usefulFile = true;
        throw new ResponseProcessingException(cce, tempFile);

    } finally {
        // clean up and delete
        if (tempFile != null) {
            if (!usefulFile)
                tempFile.delete();
            else
                tempFile.deleteOnExit();
        }
    }

    /*
    try {
       um.un
    } catch (JDOMException jdome) {
    // this document must be malformed
    usefulFile = true;
    throw new XMLParsingException(jdome, tempFile);
       } 
    } catch (IOException ioe) {
       // well, something there failed and it was lower level than just bad XML...
       if(tempFile != null) {
    usefulFile = true;
    throw new XMLParsingException(ioe, tempFile);
       }
               
       throw new XMLParsingException(ioe);
               
    } finally {
       // make sure we closed our file
       if(fileOut != null)
    fileOut.close();
               
       // make sure we delete it, too
       if(tempFile != null)
       {
    if (!usefulFile)
       tempFile.delete();
    else
       tempFile.deleteOnExit();
       }
    }
    */
}

From source file:br.com.vpsa.oauth2android.response.Response.java

private void getStringEntity() throws IOException {
    HttpEntity entity = httpResponse.getEntity();
    this.stringResponse = EntityUtils.toString(entity, EntityUtils.getContentCharSet(entity));
}

From source file:com.smartling.api.sdk.util.HttpUtils.java

/**
 * Method for executing http calls and retrieving string response.
 * @param httpRequest request for execute
 * @param proxyConfiguration proxy configuration, if it is set to {@code NULL} proxy settings will be setup from system properties. Otherwise switched off.
 * @return {@link StringResponse} the contents of the requested file along with the encoding of the file.
 * @throws com.smartling.api.sdk.exceptions.SmartlingApiException if an exception has occurred or non success is returned from the Smartling Translation API.
 *///  ww w.  java  2  s.  com
public StringResponse executeHttpCall(final HttpRequestBase httpRequest,
        final ProxyConfiguration proxyConfiguration) throws SmartlingApiException {
    CloseableHttpClient httpClient = null;
    try {
        requestId.remove();
        responseDetails.remove();

        ProxyConfiguration newProxyConfiguration = mergeSystemProxyConfiguration(proxyConfiguration);

        logProxyConfiguration(newProxyConfiguration);

        httpClient = httpProxyUtils.getHttpClient(newProxyConfiguration);

        RequestConfig proxyRequestConfig = httpProxyUtils.getProxyRequestConfig(httpRequest,
                newProxyConfiguration);

        if (proxyRequestConfig != null) {
            httpRequest.setConfig(proxyRequestConfig);
        }
        addUserAgentHeader(httpRequest);
        final HttpResponse response = httpClient.execute(httpRequest);

        final String charset = EntityUtils.getContentCharSet(response.getEntity());
        int statusCode = response.getStatusLine().getStatusCode();

        Header header = response.getFirstHeader(X_SL_REQUEST_ID);
        if (header != null) {
            requestId.set(header.getValue());
        }

        ResponseDetails details = new ResponseDetails(statusCode, response.getAllHeaders());
        responseDetails.set(details);

        return inputStreamToString(response.getEntity().getContent(), charset, statusCode);
    } catch (final IOException ioe) {
        logger.error(String.format(LOG_MESSAGE_ERROR_TEMPLATE, ioe.getMessage()));
        throw new SmartlingApiException(ioe);
    } finally {
        try {
            if (null != httpClient)
                httpClient.close();
        } catch (final IOException ioe) {
            logger.warn(String.format(LOG_MESSAGE_ERROR_TEMPLATE, ioe.getMessage()));
        }
    }
}

From source file:org.couch4j.http.DatabaseChangeNotificationService.java

private void receiveChangeNotifications() {
    if (receivingChangeNotifications) {
        return;//from ww w  . j a va  2s .c  o m
    }
    logger.info("[" + Thread.currentThread().getName() + "] Start receiveChangeNotifications()...");

    receivingChangeNotifications = true;
    executor = Executors.newSingleThreadExecutor();
    Runnable r = new Runnable() {
        private void streamChanges(int updateSeq) {
            if (!receivingChangeNotifications) {
                return;
            }
            // Do we need the "heartbeat" param?
            HttpGet method = new HttpGet(urlResolver.urlForPath("_changes", map("feed", "continuous", "style",
                    "all_docs", "since", String.valueOf(updateSeq), "heartbeat", "5000")));

            HttpResponse response = null;
            HttpEntity entity = null;
            try {
                // int statusCode = client.executeMethod(method);
                response = client.execute(method);
                entity = response.getEntity();
                // Read the response body.
                Reader in = new InputStreamReader(entity.getContent(), EntityUtils.getContentCharSet(entity));

                Scanner s = new Scanner(in).useDelimiter("\n");
                String line;
                while (s.hasNext() && null != (line = s.next())) {
                    // dispatch change event
                    if (line.length() > 1 && JSONUtils.mayBeJSON(line)) {
                        JSONObject json = JSONObject.fromObject(line);
                        if (json.has("seq")) {
                            if (logger.isLoggable(Level.FINE)) {
                                logger.fine("Dispatch new change event: " + line);
                            }
                            dispatchEvent(new DatabaseChangeEvent(json));
                        } else if (json.has("last_seq")) {
                            if (logger.isLoggable(Level.FINE)) {
                                logger.fine("CouchDB server closed _changes connection. Reconnecting...");
                            }
                            streamChanges(json.getInt("last_seq"));
                        }
                    }
                }
                if (logger.isLoggable(Level.FINE)) {
                    logger.fine("[" + Thread.currentThread().getName() + "] Stop receiving changes...");
                }
            } catch (IOException e) {
                throw new Couch4JException(e);
            } finally {
                if (null != entity) {
                    try {
                        entity.consumeContent();
                    } catch (IOException e) {
                        // swallow
                    }
                }
            }
        }

        public void run() {
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("[" + Thread.currentThread().getName() + "] Start receiving changes... ");
            }
            // Start with current udpate seq
            int updateSeq = database.getDatabaseInfo().getUpdateSeq();
            streamChanges(updateSeq);
        }
    };
    executor.submit(r);
}

From source file:com.uzmap.pkg.uzmodules.uzBMap.methods.MapGoogleCoords.java

private String getCharSet(HttpEntity httpEntity) {
    String charSet = EntityUtils.getContentCharSet(httpEntity);
    if (null == charSet) {
        charSet = "UTF-8";
    }// ww w. j  a  v  a2  s . c om
    return charSet;
}