Java Code Examples for org.apache.http.HttpEntity#getContentType()

The following examples show how to use org.apache.http.HttpEntity#getContentType() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: presto   File: ElasticsearchClient.java    License: Apache License 2.0 6 votes vote down vote up
private static PrestoException propagate(ResponseException exception)
{
    HttpEntity entity = exception.getResponse().getEntity();

    if (entity != null && entity.getContentType() != null) {
        try {
            JsonNode reason = OBJECT_MAPPER.readTree(entity.getContent()).path("error")
                    .path("root_cause")
                    .path(0)
                    .path("reason");

            if (!reason.isMissingNode()) {
                throw new PrestoException(ELASTICSEARCH_QUERY_FAILURE, reason.asText(), exception);
            }
        }
        catch (IOException e) {
            PrestoException result = new PrestoException(ELASTICSEARCH_QUERY_FAILURE, exception);
            result.addSuppressed(e);
            throw result;
        }
    }

    throw new PrestoException(ELASTICSEARCH_QUERY_FAILURE, exception);
}
 
Example 2
Source Project: RoboZombie   File: EntityUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Obtains character set of the entity, if known.
 *
 * @param entity must not be null
 * @return the character set, or null if not found
 * @throws ParseException if header elements cannot be deserialized
 * @throws IllegalArgumentException if entity is null
 *
 * @deprecated (4.1.3) use {@link ContentType#getOrDefault(HttpEntity)}
 */
@Deprecated
public static String getContentCharSet(final HttpEntity entity) throws ParseException {
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }
    String charset = null;
    if (entity.getContentType() != null) {
        HeaderElement values[] = entity.getContentType().getElements();
        if (values.length > 0) {
            NameValuePair param = values[0].getParameterByName("charset");
            if (param != null) {
                charset = param.getValue();
            }
        }
    }
    return charset;
}
 
Example 3
public HttpRequestWrapperResponse(HttpResponse response) throws IllegalArgumentException {
  if (response == null) {
    throw new IllegalArgumentException("HttpResponse cannot be null");
  }
  this.statusCode = response.getStatusLine().getStatusCode();
  this.headers = new HashSet<Header>();
  this.headers.addAll(Arrays.asList(response.getAllHeaders()));
  HttpEntity entity = response.getEntity();
  if (entity != null) {
    this.contentType = entity.getContentType();
    this.encoding = entity.getContentEncoding();
    try {
      this.contentInputStream = entity.getContent();
    } catch (IOException e) {
      throw new RuntimeException(
          "Could not get content input stream from HttpResponse:" + e.getLocalizedMessage(), e);
    }
  } else {
    this.contentType = response.getFirstHeader("Content-Type");
    this.encoding = response.getFirstHeader("Content-Encoding");
    this.contentInputStream = null;
  }
}
 
Example 4
Source Project: keycloak   File: URLAssert.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void assertResponse(CloseableHttpResponse response) throws IOException {
    HttpEntity entity = response.getEntity();
    Header contentType = entity.getContentType();
    Assert.assertEquals("application/json", contentType.getValue());

    char [] buf = new char[8192];
    StringWriter out = new StringWriter();
    Reader in = new InputStreamReader(entity.getContent(), Charset.forName("utf-8"));
    int rc;
    try {
        while ((rc = in.read(buf)) != -1) {
            out.write(buf, 0, rc);
        }
    } finally {
        try {
            in.close();
        } catch (Exception ignored) {}

        out.close();
    }

    assertResponseBody(out.toString());
}
 
Example 5
public static void copy(HttpResponse source, HttpServletResponse target) {
    int statusCode = source.getStatusLine().getStatusCode();
    target.setStatus(statusCode);
    LOGGER.info("Response from extension returned " + statusCode + " status code");

    HttpEntity entity = source.getEntity();

    Header contentType = entity.getContentType();
    if (contentType != null) {
        target.setContentType(contentType.getValue());
        LOGGER.info("Response from extension returned " + contentType.getValue() + " content type");
    }

    long contentLength = entity.getContentLength();
    target.setContentLength(Ints.checkedCast(contentLength));
    LOGGER.info("Response from extension has " + contentLength + " content length");

    LOGGER.info("Copying body content to original servlet response");
    try (InputStream content = entity.getContent();
         OutputStream response = target.getOutputStream()) {
        IOUtils.copy(content, response);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Failed to copy response body content", e);
    }
}
 
Example 6
/**
 * @param  entity  response entity.
 *
 * @return the entity content as a string if has "text/plain" mime type, otherwise null.
 *
 * @throws IOException
 *   if the entity content cannot be read.
 */
String getResponseBodyText(final HttpEntity entity)
        throws IOException {

    String text = null;

    final Header contentTypeHeader = entity.getContentType();
    if (contentTypeHeader != null) {
        final String contentTypeValue = contentTypeHeader.getValue();
        if ((contentTypeValue != null) && contentTypeValue.startsWith(TEXT_PLAIN_MIME_TYPE)) {
            text = IOUtils.toString(entity.getContent());
        }
    }

    return text;
}
 
Example 7
/**
 * copy: EntityUtils Obtains character set of the entity, if known.
 *
 * @param entity must not be null
 * @return the character set, or null if not found
 * @throws ParseException           if header elements cannot be parsed
 * @throws IllegalArgumentException if entity is null
 */
private static String getContentCharSet(final HttpEntity entity) throws ParseException {
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity must not be null");
    }
    String charset = null;
    if (entity.getContentType() != null) {
        HeaderElement values[] = entity.getContentType().getElements();
        if (values.length > 0) {
            NameValuePair param = values[0].getParameterByName("charset");
            if (param != null) {
                charset = param.getValue();
            }
        }
    }
    return charset;
}
 
Example 8
Source Project: karate   File: LoggingUtils.java    License: MIT License 5 votes vote down vote up
public static boolean isPrintable(HttpEntity entity) {
    if (entity == null) {
        return false;
    }
    return entity.getContentType() != null
                && HttpUtils.isPrintable(entity.getContentType().getValue());
}
 
Example 9
Source Project: RoboZombie   File: URLEncodedUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the entity's Content-Type header is
 * <code>application/x-www-form-urlencoded</code>.
 */
public static boolean isEncoded (final HttpEntity entity) {
    Header h = entity.getContentType();
    if (h != null) {
        HeaderElement[] elems = h.getElements();
        if (elems.length > 0) {
            String contentType = elems[0].getName();
            return contentType.equalsIgnoreCase(CONTENT_TYPE);
        } else {
            return false;
        }
    } else {
        return false;
    }
}
 
Example 10
public String getContentType() {
    HttpEntity responseEntity = resp.getEntity();
    if (responseEntity != null) {
        Header contentType = responseEntity.getContentType();
        if (contentType != null)
            return contentType.getValue();
    }
    return null;
}
 
Example 11
Source Project: esigate   File: ResponseSender.java    License: Apache License 2.0 5 votes vote down vote up
void sendHeaders(HttpResponse httpResponse, IncomingRequest httpRequest, HttpServletResponse response) {
    response.setStatus(httpResponse.getStatusLine().getStatusCode());
    for (Header header : httpResponse.getAllHeaders()) {
        String name = header.getName();
        String value = header.getValue();
        response.addHeader(name, value);
    }

    // Copy new cookies
    Cookie[] newCookies = httpRequest.getNewCookies();

    for (Cookie newCooky : newCookies) {

        // newCooky may be null. In that case just ignore.
        // See https://github.com/esigate/esigate/issues/181
        if (newCooky != null) {
            response.addHeader("Set-Cookie", CookieUtil.encodeCookie(newCooky));
        }
    }
    HttpEntity httpEntity = httpResponse.getEntity();
    if (httpEntity != null) {
        long contentLength = httpEntity.getContentLength();
        if (contentLength > -1 && contentLength < Integer.MAX_VALUE) {
            response.setContentLength((int) contentLength);
        }
        Header contentType = httpEntity.getContentType();
        if (contentType != null) {
            response.setContentType(contentType.getValue());
        }
        Header contentEncoding = httpEntity.getContentEncoding();
        if (contentEncoding != null) {
            response.setHeader(contentEncoding.getName(), contentEncoding.getValue());
        }
    }
}
 
Example 12
/**
 * Returns true if the entity's Content-Type header is
 * <code>application/x-www-form-urlencoded</code>.
 */
public static boolean isEncoded(final HttpEntity entity) {
    Header h = entity.getContentType();
    if (h != null) {
        HeaderElement[] elems = h.getElements();
        if (elems.length > 0) {
            String contentType = elems[0].getName();
            return contentType.equalsIgnoreCase(CONTENT_TYPE);
        } else {
            return false;
        }
    } else {
        return false;
    }
}
 
Example 13
@Override
public String getContentType() {
  HttpEntity entity = response.getEntity();
  if (entity != null) {
    Header contentTypeHeader = entity.getContentType();
    if (contentTypeHeader != null) {
      return contentTypeHeader.getValue();
    }
  }
  return null;
}
 
Example 14
Source Project: RoboZombie   File: EntityUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Obtains mime type of the entity, if known.
 *
 * @param entity must not be null
 * @return the character set, or null if not found
 * @throws ParseException if header elements cannot be deserialized
 * @throws IllegalArgumentException if entity is null
 *
 * @since 4.1
 *
 * @deprecated (4.1.3) use {@link ContentType#getOrDefault(HttpEntity)}
 */
@Deprecated
public static String getContentMimeType(final HttpEntity entity) throws ParseException {
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }
    String mimeType = null;
    if (entity.getContentType() != null) {
        HeaderElement values[] = entity.getContentType().getElements();
        if (values.length > 0) {
            mimeType = values[0].getName();
        }
    }
    return mimeType;
}
 
Example 15
protected JSONArray fetchTransform(HttpRequestEntity request)
        throws IOException {

    String transformURI = getSingleParameter(TRANSFORM_PARAMETER,
            request.getRequest());

    CloseableHttpClient client = null;
    CloseableHttpResponse response = null;

    try {
        HttpGet get = new HttpGet(transformURI);
        get.addHeader("Accept", "application/json");

        client = HttpClients.createDefault();
        response = performRequest(get, client);

        HttpEntity responseEntity = response.getEntity();
        if (responseEntity == null) {
            // TODO proper error reporting
            throw new IOException("Could not GET transform JSON from "
                    + transformURI + ".");
        }

        String encoding = null;
        if (responseEntity.getContentType() != null) {
            encoding = MimeTypes.getCharsetFromContentType(responseEntity.getContentType().getValue());
        }

        String transform = IOUtils.toString(responseEntity.getContent(),
                encoding == null ? "UTF-8" : encoding);

        return ParsingUtilities.evaluateJsonStringToArray(transform);
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(client);
    }
}
 
Example 16
Source Project: RoboZombie   File: ContentType.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Extracts <code>Content-Type</code> value from {@link HttpEntity} exactly as
 * specified by the <code>Content-Type</code> header of the entity. Returns <code>null</code>
 * if not specified.
 *
 * @param entity HTTP entity
 * @return content type
 * @throws ParseException if the given text does not represent a valid
 * <code>Content-Type</code> value.
 */
public static ContentType get(
        final HttpEntity entity) throws ParseException, UnsupportedCharsetException {
    if (entity == null) {
        return null;
    }
    Header header = entity.getContentType();
    if (header != null) {
        HeaderElement[] elements = header.getElements();
        if (elements.length > 0) {
            return create(elements[0]);
        }
    }
    return null;
}
 
Example 17
Source Project: restfiddle   File: GenericHandler.java    License: Apache License 2.0 5 votes vote down vote up
private RfResponseDTO buildRfResponse(CloseableHttpResponse httpResponse) throws IOException {
RfResponseDTO responseDTO = new RfResponseDTO();
String responseBody = "";
List<RfHeaderDTO> headers = new ArrayList<RfHeaderDTO>();
try {
    logger.info("response status : " + httpResponse.getStatusLine());
    responseDTO.setStatus(httpResponse.getStatusLine().getStatusCode() + " " + httpResponse.getStatusLine().getReasonPhrase());
    HttpEntity responseEntity = httpResponse.getEntity();
    Header[] responseHeaders = httpResponse.getAllHeaders();

    RfHeaderDTO headerDTO = null;
    for (Header responseHeader : responseHeaders) {
	// logger.info("response header - name : " + responseHeader.getName() + " value : " + responseHeader.getValue());
	headerDTO = new RfHeaderDTO();
	headerDTO.setHeaderName(responseHeader.getName());
	headerDTO.setHeaderValue(responseHeader.getValue());
	headers.add(headerDTO);
    }
    Header contentType = responseEntity.getContentType();
    logger.info("response contentType : " + contentType);

    // logger.info("content : " + EntityUtils.toString(responseEntity));
    responseBody = EntityUtils.toString(responseEntity);
    EntityUtils.consume(responseEntity);
} finally {
    httpResponse.close();
}
responseDTO.setBody(responseBody);
responseDTO.setHeaders(headers);
return responseDTO;
   }
 
Example 18
Source Project: ongdb-lab-apoc   File: Dictionary.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 从远程服务器上下载自定义词条
 */
private static List<String> getRemoteWordsUnprivileged(String location) {

    List<String> buffer = new ArrayList<String>();
    RequestConfig rc = RequestConfig.custom().setConnectionRequestTimeout(10 * 1000).setConnectTimeout(10 * 1000)
            .setSocketTimeout(60 * 1000).build();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response;
    BufferedReader in;
    HttpGet get = new HttpGet(location);
    get.setConfig(rc);
    try {
        response = httpclient.execute(get);
        if (response.getStatusLine().getStatusCode() == 200) {

            String charset = "UTF-8";
            // 获取编码,默认为utf-8
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header contentType = entity.getContentType();
                if (contentType != null && contentType.getValue() != null) {
                    String typeValue = contentType.getValue();
                    if (typeValue != null && typeValue.contains("charset=")) {
                        charset = typeValue.substring(typeValue.lastIndexOf("=") + 1);
                    }
                }

                if (entity.getContentLength() > 0) {
                    in = new BufferedReader(new InputStreamReader(entity.getContent(), charset));
                    String line;
                    while ((line = in.readLine()) != null) {
                        buffer.add(line);
                    }
                    in.close();
                    response.close();
                    return buffer;
                }
            }
        }
        response.close();
    } catch (IllegalStateException | IOException e) {
        logger.error("getRemoteWords " + location + " error", e);
    }
    return buffer;
}
 
Example 19
Source Project: product-emm   File: ServerUtilities.java    License: Apache License 2.0 4 votes vote down vote up
public static String getContentCharSet(final HttpEntity entity) throws ParseException {

		String charSet = null;

		if (entity.getContentType() != null) {
			HeaderElement values[] = entity.getContentType().getElements();

			if (values.length > 0) {
				NameValuePair param = values[0].getParameterByName("charset");

				if (param != null) {
					charSet = param.getValue();
				}
			}
		}

		return charSet;

	}
 
Example 20
private void checkContentType(HttpEntity entity) throws RestApiException {
    Header contentType = entity.getContentType();
    if (contentType != null && !contentType.getValue().contains(JSON_MIME_TYPE)) {
        throw new RestApiException(String.format("Expected JSON but got '%s'.", contentType.getValue()));
    }
}