Example usage for org.apache.http.entity ContentType getCharset

List of usage examples for org.apache.http.entity ContentType getCharset

Introduction

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

Prototype

public Charset getCharset() 

Source Link

Usage

From source file:interoperabilite.webservice.fluent.FluentResponseHandling.java

public static void main(String[] args) throws Exception {
    Document result = Request.Get("http://somehost/content").execute()
            .handleResponse(new ResponseHandler<Document>() {

                @Override/*from w  w  w  .ja v  a 2 s  .com*/
                public Document handleResponse(final HttpResponse response) throws IOException {
                    StatusLine statusLine = response.getStatusLine();
                    HttpEntity entity = response.getEntity();
                    if (statusLine.getStatusCode() >= 300) {
                        throw new HttpResponseException(statusLine.getStatusCode(),
                                statusLine.getReasonPhrase());
                    }
                    if (entity == null) {
                        throw new ClientProtocolException("Response contains no content");
                    }
                    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
                    try {
                        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
                        ContentType contentType = ContentType.getOrDefault(entity);
                        if (!contentType.equals(ContentType.APPLICATION_XML)) {
                            throw new ClientProtocolException("Unexpected content type:" + contentType);
                        }
                        Charset charset = contentType.getCharset();
                        if (charset == null) {
                            charset = Consts.ISO_8859_1;
                        }
                        return docBuilder.parse(entity.getContent(), charset.name());
                    } catch (ParserConfigurationException ex) {
                        throw new IllegalStateException(ex);
                    } catch (SAXException ex) {
                        throw new ClientProtocolException("Malformed XML document", ex);
                    }
                }

            });
    // Do something useful with the result
    System.out.println(result);
}

From source file:io.aos.protocol.http.httpcommon.FluentResponseHandling.java

public static void main(String... args) throws Exception {
    Document result = Request.Get("http://somehost/content").execute()
            .handleResponse(new ResponseHandler<Document>() {

                public Document handleResponse(final HttpResponse response) throws IOException {
                    StatusLine statusLine = response.getStatusLine();
                    HttpEntity entity = response.getEntity();
                    if (statusLine.getStatusCode() >= 300) {
                        throw new HttpResponseException(statusLine.getStatusCode(),
                                statusLine.getReasonPhrase());
                    }//from w ww .  ja  v  a2s  .  com
                    if (entity == null) {
                        throw new ClientProtocolException("Response contains no content");
                    }
                    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
                    try {
                        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
                        ContentType contentType = ContentType.getOrDefault(entity);
                        if (!contentType.equals(ContentType.APPLICATION_XML)) {
                            throw new ClientProtocolException("Unexpected content type:" + contentType);
                        }
                        Charset charset = contentType.getCharset();
                        if (charset == null) {
                            charset = HTTP.DEF_CONTENT_CHARSET;
                        }
                        return docBuilder.parse(entity.getContent(), charset.name());
                    } catch (ParserConfigurationException ex) {
                        throw new IllegalStateException(ex);
                    } catch (SAXException ex) {
                        throw new ClientProtocolException("Malformed XML document", ex);
                    }
                }

            });
    // Do something useful with the result
    System.out.println(result);
}

From source file:com.github.parisoft.resty.utils.MediaTypeUtils.java

public static MediaType valueOf(ContentType contentType) {
    final String[] mime = StringUtils.splitOnSlashes(contentType.getMimeType());
    final String charset = contentType.getCharset() != null ? contentType.getCharset().toString() : null;

    return new MediaType(mime[0], mime[1], charset);
}

From source file:org.ambraproject.wombat.service.remote.ReaderService.java

private static Charset getCharsetOrDefault(HttpEntity entity) {
    Charset charset = null;// w ww.  ja  v  a2 s  .c o  m
    ContentType contentType = ContentType.get(Preconditions.checkNotNull(entity));
    if (contentType != null) {
        charset = contentType.getCharset(); // may be null
    }
    if (charset == null) {
        log.warn("Charset not specified in response header; defaulting to {}", DEFAULT_CHARSET.name());
        charset = DEFAULT_CHARSET;
    }
    return charset;
}

From source file:net.javacrumbs.restfire.httpcomponents.HttpComponentsResponse.java

private static Charset getCharset(HttpEntity entity) {
    Charset charset = null;/*from  w  w  w  .j  a  va 2  s.c  o  m*/
    ContentType contentType = ContentType.get(entity);
    if (contentType != null) {
        charset = contentType.getCharset();
    }
    if (charset == null) {
        charset = HTTP.DEF_CONTENT_CHARSET;
    }
    return charset;
}

From source file:co.cask.cdap.client.rest.RestClient.java

/**
 * Utility method for converting {@link org.apache.http.HttpEntity} HTTP entity content to String.
 *
 * @param httpEntity {@link org.apache.http.HttpEntity}
 * @return {@link String} generated from input content stream
 * @throws IOException if HTTP entity is not available
 *//* ww w.  j ava 2  s.com*/
public static String toString(HttpEntity httpEntity) throws IOException {
    if (httpEntity == null || httpEntity.getContent() == null) {
        throw new IOException("Empty HttpEntity is received.");
    }
    Charset charset = Charsets.UTF_8;
    ContentType contentType = ContentType.get(httpEntity);
    if (contentType != null && contentType.getCharset() != null) {
        charset = contentType.getCharset();
    }
    Reader reader = new InputStreamReader(httpEntity.getContent(), charset);
    try {
        return CharStreams.toString(reader);
    } finally {
        reader.close();
    }
}

From source file:com.helger.httpclient.HttpClientHelper.java

@Nullable
public static Charset getCharset(@Nonnull final ContentType aContentType, @Nullable final Charset aDefault) {
    final Charset ret = aContentType.getCharset();
    return ret != null ? ret : aDefault;
}

From source file:de.l3s.boilerpipe.sax.HTMLFetcher.java

public static HTMLDocument fetch(final String url) throws IOException {
    //DefaultHttpClient httpclient = new DefaultHttpClient();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet request = new HttpGet(url.toString());
    request.setHeader("User-Agent",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.104 Safari/537.36");
    request.setHeader("Referer", "http://www.google.com");

    HttpResponse response = httpclient.execute(request);
    HttpEntity entity = response.getEntity();
    //System.out.println("Response Code: " +
    //response.getStatusLine().getStatusCode());
    ContentType contentType = ContentType.getOrDefault(entity);
    Charset charset = contentType.getCharset();
    if (charset == null) {
        charset = Charset.forName("gb2312");
    }//from  w  ww.ja v a 2s.co  m

    BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent(), charset));

    StringBuilder builder = new StringBuilder();
    String aux = "";
    Charset cs = Charset.forName("utf8");
    boolean charsetFlag = false;
    while ((aux = rd.readLine()) != null) {
        if (aux != null && !charsetFlag && (aux.contains("http-equiv") || !aux.contains("src"))) {
            Matcher m = PAT_CHARSET_REX.matcher(aux);
            if (m.find()) {
                final String cName = m.group(1);
                charsetFlag = true;
                try {
                    cs = Charset.forName(cName);
                    break;
                } catch (UnsupportedCharsetException e) {
                    // keep default
                }
            }
        }
        //builder.append(aux);
        //System.out.println(builder.toString());
    }

    HttpGet request2 = new HttpGet(url.toString());
    request2.setHeader("User-Agent",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.104 Safari/537.36");
    request2.setHeader("Referer", "http://www.google.com");

    HttpResponse response2 = httpclient.execute(request2);
    HttpEntity entity2 = response2.getEntity();
    contentType = ContentType.getOrDefault(entity2);
    charset = contentType.getCharset();
    if (charset == null)
        charset = cs;
    //if(charset.name().toLowerCase().equals("gb2312"))
    //   charset = Charset.forName("gbk");
    BufferedReader rd2 = new BufferedReader(new InputStreamReader(entity2.getContent(), charset));
    while ((aux = rd2.readLine()) != null) {
        builder.append(aux);
        //System.out.println(builder.toString());
    }

    String text = builder.toString();
    //System.out.println(text);
    rd.close();
    rd2.close();
    return new HTMLDocument(text, cs); //sometimes cs not equal to charset
}

From source file:org.apache.manifoldcf.authorities.authorities.jira.JiraSession.java

private static Charset getCharSet(HttpEntity entity) {
    Charset charSet;/*w  w  w.  ja  v a 2s .  c o m*/
    try {
        ContentType ct = ContentType.get(entity);
        if (ct == null)
            charSet = StandardCharsets.UTF_8;
        else
            charSet = ct.getCharset();
    } catch (ParseException e) {
        charSet = StandardCharsets.UTF_8;
    }
    return charSet;
}

From source file:com.mirth.connect.server.userutil.HTTPUtil.java

/**
 * Serializes an HTTP request body into XML. Multipart requests will also automatically be
 * parsed into separate XML nodes.//from w  w  w.jav  a 2  s  .  c o  m
 * 
 * @param httpBody
 *            The request body/payload input stream to parse.
 * @param contentType
 *            The MIME content type of the request.
 * @return The serialized XML string.
 * @throws MessagingException
 * @throws IOException
 * @throws DonkeyElementException
 * @throws ParserConfigurationException
 */
public static String httpBodyToXml(InputStream httpBody, String contentType)
        throws MessagingException, IOException, DonkeyElementException, ParserConfigurationException {
    ContentType type = getContentType(contentType);
    Object content;

    if (type.getMimeType().startsWith(FileUploadBase.MULTIPART)) {
        content = new MimeMultipart(new ByteArrayDataSource(httpBody, type.toString()));
    } else {
        content = IOUtils.toString(httpBody,
                HttpMessageConverter.getDefaultHttpCharset(type.getCharset().name()));
    }

    return HttpMessageConverter.contentToXml(content, type, true, null);
}