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

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

Introduction

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

Prototype

public static ContentType get(HttpEntity httpEntity) throws ParseException, UnsupportedCharsetException 

Source Link

Usage

From source file:com.nominanuda.web.http.BaseHttpTest.java

protected String asString(HttpResponse resp) throws ClientProtocolException, IOException {
    HttpEntity entity = resp.getEntity();
    try {/* w  ww .  ja va  2 s  . c o  m*/
        if (HttpStatus.SC_OK != resp.getStatusLine().getStatusCode()) {
            throw new RuntimeException();
        }
        Charset cs = ContentType.get(entity).getCharset();
        return new String(io.readAndClose(entity.getContent()), cs == null ? CS_UTF_8 : cs);
    } finally {
        EntityUtils.consume(entity);
    }
}

From source file:org.esigate.http.HttpResponseUtils.java

public static ContentType getContentType(CloseableHttpResponse response) {
    HttpEntity entity = response.getEntity();
    if (entity == null) {
        return null;
    }/*from  ww w.j a  v a 2s. c  om*/
    return ContentType.get(entity);
}

From source file:org.apache.manifoldcf.crawler.connectors.confluence.ConfluenceSession.java

private static Charset getCharSet(HttpEntity entity) {
    Charset charSet;//  w w w  . j a v  a  2s  . co  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;
    }

    // assign UTF-8 as standard charset if no char set is inferred
    if (charSet == null) {
        charSet = StandardCharsets.UTF_8;
    }
    if (Logging.connectors != null)
        Logging.connectors.info("Charset : " + charSet.toString());
    return charSet;
}

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

private static Charset getCharSet(HttpEntity entity) {
    Charset charSet;//w  w  w.j a  v  a 2  s. c  om
    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:uk.ac.susx.tag.method51.webapp.handler.CodingInstanceHandler.java

/**
 * Re-issue the request to an instance.//from  w  ww . ja  v  a2s  .c  o  m
 *
 * @param target
 * @param baseRequest
 * @param request
 * @param response
 * @throws IOException
 */
private void coding(final String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    new DoSomethingWithTheSpecifiedJobID(request, response) {

        public void something(String jid) throws IOException {

            Integer port = project.m51(jid).getPort();

            //int port = ((Number)j.getMeta("port")).intValue();

            HttpClient httpclient = new DefaultHttpClient();

            String method = request.getMethod();

            String target = "/coding" + request.getParameter("_target");

            URIBuilder builder = new URIBuilder();

            Set<String> ignore = new HashSet<>();
            ignore.add("id");
            ignore.add("_target");

            builder.setHost("localhost").setScheme("http").setPort(port).setPath(target);

            try {

                HttpUriRequest uriRequest;

                if ("GET".equals(method)) {
                    for (Map.Entry<String, String[]> e : request.getParameterMap().entrySet()) {
                        String key = e.getKey();
                        if (!ignore.contains(key)) {
                            builder.setParameter(e.getKey(), e.getValue()[0]);
                        }
                    }
                    URI uri = builder.build();
                    uriRequest = new HttpGet(uri);
                } else {
                    URI uri = builder.build();
                    List<NameValuePair> params = new ArrayList<>();
                    for (Map.Entry<String, String[]> e : request.getParameterMap().entrySet()) {
                        String key = e.getKey();
                        if (!ignore.contains(key)) {
                            params.add(new BasicNameValuePair(key, e.getValue()[0]));
                        }
                    }
                    uriRequest = new HttpPost(uri);
                    ((HttpPost) uriRequest).setEntity(new UrlEncodedFormEntity(params));
                }

                LOG.info("re-issuing request: {}", uriRequest.toString());

                HttpResponse r = httpclient.execute(uriRequest);

                StatusLine statusLine = r.getStatusLine();
                HttpEntity entity = r.getEntity();
                if (statusLine.getStatusCode() >= 400) {
                    try {
                        ContentType contentType = ContentType.get(entity);
                        String responseBody = EntityUtils.toString(entity, contentType.getCharset());
                        throw new RequestException(statusLine.getReasonPhrase() + responseBody,
                                statusLine.getStatusCode());
                    } catch (IOException | ParseException | NullPointerException e) {
                        EntityUtils.consume(entity);
                        throw new RequestException(statusLine.getReasonPhrase(), statusLine.getStatusCode());
                    }
                }

                response.setStatus(statusLine.getStatusCode());

                ContentType contentType = ContentType.get(entity);
                if (contentType == null) {
                    error("null content type!", response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                } else {
                    String responseBody = EntityUtils.toString(entity, contentType.getCharset());

                    response.setContentType(contentType.toString());
                    response.setCharacterEncoding(contentType.getCharset().toString());
                    response.getWriter().print(responseBody);
                }

            } catch (URISyntaxException e) {
                error(e.getMessage(), response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        }
    };
}

From source file:org.robertburrelldonkin.template4couchdb.rest.HttpClientRestClientTest.java

@Test
public void testPostMediaType() throws Exception {
    ArgumentCaptor<HttpPost> argument = ArgumentCaptor.forClass(HttpPost.class);
    this.subject.post(URL, documentMarshaller, document, responseUnmarshaller);
    verify(client).execute(argument.capture(), eq(handler));
    final ContentType contentType = ContentType.get(argument.getValue().getEntity());
    assertThat(contentType.getMimeType(), is("application/json"));
    assertThat(contentType.getCharset(), is(Consts.UTF_8));
}

From source file:net.yacy.grid.http.ClientConnection.java

private void init() throws IOException {

    this.httpResponse = null;
    try {//from  w  ww .  j  a v a2s  .co m
        this.httpResponse = httpClient.execute(this.request);
    } catch (UnknownHostException e) {
        this.request.releaseConnection();
        throw new IOException("client connection failed: unknown host " + this.request.getURI().getHost());
    } catch (SocketTimeoutException e) {
        this.request.releaseConnection();
        throw new IOException("client connection timeout for request: " + this.request.getURI());
    } catch (SSLHandshakeException e) {
        this.request.releaseConnection();
        throw new IOException("client connection handshake error for domain " + this.request.getURI().getHost()
                + ": " + e.getMessage());
    }
    HttpEntity httpEntity = this.httpResponse.getEntity();
    this.contentType = ContentType.get(httpEntity);
    if (httpEntity != null) {
        if (this.httpResponse.getStatusLine().getStatusCode() == 200) {
            try {
                this.inputStream = new BufferedInputStream(httpEntity.getContent());
            } catch (IOException e) {
                this.request.releaseConnection();
                throw e;
            }
            this.header = new HashMap<String, List<String>>();
            for (Header header : httpResponse.getAllHeaders()) {
                List<String> vals = this.header.get(header.getName());
                if (vals == null) {
                    vals = new ArrayList<String>();
                    this.header.put(header.getName(), vals);
                }
                vals.add(header.getValue());
            }
        } else {
            this.request.releaseConnection();
            throw new IOException("client connection to " + this.request.getURI() + " fail: " + status + ": "
                    + httpResponse.getStatusLine().getReasonPhrase());
        }
    } else {
        this.request.releaseConnection();
        throw new IOException("client connection to " + this.request.getURI() + " fail: no connection");
    }
}

From source file:org.apache.hadoop.gateway.dispatch.DefaultDispatch.java

private String getInboundResponseContentType(final HttpEntity entity) {
    String fullContentType = null;
    if (entity != null) {
        ContentType entityContentType = ContentType.get(entity);
        if (entityContentType != null) {
            if (entityContentType.getCharset() == null) {
                final String entityMimeType = entityContentType.getMimeType();
                final String defaultCharset = MimeTypes.getDefaultCharsetForMimeType(entityMimeType);
                if (defaultCharset != null) {
                    LOG.usingDefaultCharsetForEntity(entityMimeType, defaultCharset);
                    entityContentType = entityContentType.withCharset(defaultCharset);
                }//w  w w .  j  a  v a  2 s  .  com
            } else {
                LOG.usingExplicitCharsetForEntity(entityContentType.getMimeType(),
                        entityContentType.getCharset());
            }
            fullContentType = entityContentType.toString();
        }
    }
    if (fullContentType == null) {
        LOG.unknownResponseEntityContentType();
    } else {
        LOG.inboundResponseEntityContentType(fullContentType);
    }
    return fullContentType;
}