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

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

Introduction

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

Prototype

public String getMimeType() 

Source Link

Usage

From source file:com.qwazr.utils.http.HttpUtils.java

/**
 * Check if the entity has the expected mime type. The charset is not
 * checked./* w ww  .j  av a2  s . c  o m*/
 *
 * @param response            The response to check
 * @param expectedContentType The expected content type
 * @return the entity from the response body
 * @throws ClientProtocolException if the response does not contains any entity
 */
public static HttpEntity checkIsEntity(HttpResponse response, ContentType expectedContentType)
        throws ClientProtocolException {
    if (response == null)
        throw new ClientProtocolException("No response");
    HttpEntity entity = response.getEntity();
    if (entity == null)
        throw new ClientProtocolException("Response does not contains any content entity");
    if (expectedContentType == null)
        return entity;
    ContentType contentType = ContentType.get(entity);
    if (contentType == null)
        throw new HttpResponseEntityException(response, "Unknown content type");
    if (!expectedContentType.getMimeType().equals(contentType.getMimeType()))
        throw new HttpResponseEntityException(response,
                StringUtils.fastConcat("Wrong content type: ", contentType.getMimeType()));
    return entity;
}

From source file:com.vmware.identity.openidconnect.client.OIDCClientUtils.java

static HttpResponse sendSecureRequest(HttpRequest httpRequest, SSLContext sslContext)
        throws OIDCClientException, SSLConnectionException {
    Validate.notNull(httpRequest, "httpRequest");
    Validate.notNull(sslContext, "sslContext");

    RequestConfig config = RequestConfig.custom().setConnectTimeout(HTTP_CLIENT_TIMEOUT_MILLISECS)
            .setConnectionRequestTimeout(HTTP_CLIENT_TIMEOUT_MILLISECS)
            .setSocketTimeout(HTTP_CLIENT_TIMEOUT_MILLISECS).build();

    CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setDefaultRequestConfig(config)
            .build();/*w  w  w  .  ja  v  a 2 s.co m*/

    CloseableHttpResponse closeableHttpResponse = null;

    try {
        HttpRequestBase httpTask = httpRequest.toHttpTask();
        closeableHttpResponse = client.execute(httpTask);

        int statusCodeInt = closeableHttpResponse.getStatusLine().getStatusCode();
        StatusCode statusCode;
        try {
            statusCode = StatusCode.parse(statusCodeInt);
        } catch (ParseException e) {
            throw new OIDCClientException("failed to parse status code", e);
        }
        JSONObject jsonContent = null;
        HttpEntity httpEntity = closeableHttpResponse.getEntity();
        if (httpEntity != null) {
            ContentType contentType;
            try {
                contentType = ContentType.get(httpEntity);
            } catch (UnsupportedCharsetException | org.apache.http.ParseException e) {
                throw new OIDCClientException("Error in setting content type in HTTP response.");
            }
            if (!StandardCharsets.UTF_8.equals(contentType.getCharset())) {
                throw new OIDCClientException("unsupported charset: " + contentType.getCharset());
            }
            if (!ContentType.APPLICATION_JSON.getMimeType().equalsIgnoreCase(contentType.getMimeType())) {
                throw new OIDCClientException("unsupported mime type: " + contentType.getMimeType());
            }
            String content = EntityUtils.toString(httpEntity);
            try {
                jsonContent = JSONUtils.parseJSONObject(content);
            } catch (ParseException e) {
                throw new OIDCClientException("failed to parse json response", e);
            }
        }

        closeableHttpResponse.close();
        client.close();

        return HttpResponse.createJsonResponse(statusCode, jsonContent);
    } catch (IOException e) {
        throw new OIDCClientException("IOException caught in HTTP communication:" + e.getMessage(), e);
    }
}

From source file:org.openscore.content.httpclient.build.ContentTypeBuilderTest.java

@Test
public void buildContentTypeWithDefaultValues() {
    ContentType contentType = new ContentTypeBuilder().buildContentType();

    assertEquals(TEXT_PLAIN_CONTENT_TYPE, contentType.getMimeType().toString());
    assertEquals(Consts.ISO_8859_1.name(), contentType.getCharset().name());
}

From source file:co.com.soinsoftware.altablero.utils.HttpRequest.java

@Override
public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
    int status = response.getStatusLine().getStatusCode();
    if (status >= 200 && status < 300) {
        HttpEntity entity = response.getEntity();
        final ContentType contentType = ContentType.getOrDefault(entity);
        if (contentType.getMimeType().equals(ContentType.APPLICATION_OCTET_STREAM.getMimeType())) {
            InputStream inputStream = null;
            byte[] zipInBytes = EntityUtils.toByteArray(entity);
            if (zipInBytes != null) {
                inputStream = new ByteArrayInputStream(zipInBytes);
            }//from  w w  w .  j a v a  2 s.co  m
            return inputStream;
        }
        return entity != null ? EntityUtils.toString(entity) : null;
    } else {
        throw new ClientProtocolException(EXCEPTION_MESSAGE + status);
    }
}

From source file:lucee.commons.net.http.httpclient.entity.ByteArrayHttpEntity.java

public ByteArrayHttpEntity(byte[] barr, ContentType contentType) {
    super(barr);//  w ww.  jav a  2s  .  c o  m
    contentLength = barr == null ? 0 : barr.length;

    if (ct == null) {
        Header h = getContentType();
        if (h != null) {
            lucee.commons.lang.mimetype.ContentType tmp = HTTPUtil.toContentType(h.getValue(), null);
            if (tmp != null)
                ct = ContentType.create(tmp.getMimeType(), tmp.getCharset());
        }
    } else
        this.ct = contentType;
}

From source file:org.craftercms.studio.impl.v1.web.http.MultiReadHttpServletRequestWrapper.java

private Iterable<NameValuePair> decodeParams(String body) {
    List<NameValuePair> params = new ArrayList<>(URLEncodedUtils.parse(body, UTF8_CHARSET));
    try {//from   w w  w .j  a  v  a 2s. co  m
        String cts = getContentType();
        if (cts != null) {
            ContentType ct = ContentType.parse(cts);
            if (ct.getMimeType().equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
                List<NameValuePair> postParams = URLEncodedUtils.parse(IOUtils.toString(getReader()),
                        UTF8_CHARSET);
                CollectionUtils.addAll(params, postParams);
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    return params;
}

From source file:ca.uhn.fhir.rest.client.apache.ApacheHttpResponse.java

@Override
public String getMimeType() {
    ContentType ct = ContentType.get(myResponse.getEntity());
    return ct != null ? ct.getMimeType() : null;
}

From source file:au.csiro.casda.sodalint.Validator.java

/**
 * Retrieve the content from an address using a GET request.
 *  /*w ww  .ja v a2 s.c  o m*/
 * @param address The address to be queried.
 * @return The content, or null if no content could be read.
 * @throws HttpResponseException If a non 200 response code is returned.
 * @throws UnsupportedEncodingException If the content does not have an XML format. 
 * @throws IOException If the content could not be read.
 */
protected String getXmlContentFromUrl(String address)
        throws HttpResponseException, UnsupportedEncodingException, IOException {
    Response response = Request.Get(address).execute();
    HttpResponse httpResponse = response.returnResponse();
    StatusLine statusLine = httpResponse.getStatusLine();
    final int statusCodeOk = 200;
    if (statusLine.getStatusCode() != statusCodeOk) {
        throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
    }
    HttpEntity entity = httpResponse.getEntity();
    if (entity == null) {
        return null;
    }
    ContentType contentType = ContentType.getOrDefault(entity);
    if (!ContentType.APPLICATION_XML.getMimeType().equals(contentType.getMimeType())
            && !ContentType.TEXT_XML.getMimeType().equals(contentType.getMimeType())) {
        throw new UnsupportedEncodingException(contentType.toString());
    }
    String content = readTextContent(entity);
    if (StringUtils.isBlank(content)) {
        return null;
    }

    return content;
}

From source file:com.blacklocus.jres.handler.JresJsonResponseHandler.java

<RESPONSE extends JresReply> Pair<JsonNode, RESPONSE> read(HttpResponse http, Class<RESPONSE> responseClass) {
    if (http.getEntity() == null) {
        return null;

    } else {/*from www  .  j a va 2s . c  o  m*/
        ContentType contentType = ContentType.parse(http.getEntity().getContentType().getValue());
        if (ContentType.APPLICATION_JSON.getMimeType().equals(contentType.getMimeType())) {
            try {

                JsonNode node = ObjectMappers.fromJson(http.getEntity().getContent(), JsonNode.class);
                if (LOG.isDebugEnabled()) {
                    LOG.debug(ObjectMappers.toJson(node));
                }
                return Pair.of(node,
                        responseClass == null ? null : ObjectMappers.fromJson(node, responseClass));

            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        } else {
            throw new RuntimeException("Unable to read content with " + contentType
                    + ". This ResponseHandler can only decode " + ContentType.APPLICATION_JSON);
        }
    }
}

From source file:io.cloudslang.content.httpclient.build.ContentTypeBuilderTest.java

@Test
public void buildContentType() {
    ContentType contentType = new ContentTypeBuilder().setContentType(APPLICATION_JSON_CONTENT_TYPE)
            .setRequestCharacterSet(Consts.UTF_8.name()).buildContentType();

    assertEquals(APPLICATION_JSON_CONTENT_TYPE, contentType.getMimeType().toString());
    assertEquals(Consts.UTF_8.name(), contentType.getCharset().name());
}