org.apache.http.HttpEntity#getContentType ( )源码实例Demo

下面列出了org.apache.http.HttpEntity#getContentType ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: presto   文件: ElasticsearchClient.java
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);
}
 
源代码2 项目: RoboZombie   文件: EntityUtils.java
/**
 * 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;
}
 
源代码3 项目: rh-che   文件: HttpRequestWrapperResponse.java
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;
  }
}
 
源代码4 项目: keycloak   文件: URLAssert.java
@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());
}
 
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);
    }
}
 
源代码6 项目: render   文件: BaseResponseHandler.java
/**
 * @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;
}
 
源代码7 项目: pinpoint   文件: HttpClient4EntityExtractor.java
/**
 * 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;
}
 
源代码8 项目: karate   文件: LoggingUtils.java
public static boolean isPrintable(HttpEntity entity) {
    if (entity == null) {
        return false;
    }
    return entity.getContentType() != null
                && HttpUtils.isPrintable(entity.getContentType().getValue());
}
 
源代码9 项目: RoboZombie   文件: URLEncodedUtils.java
/**
 * 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;
    }
}
 
public String getContentType() {
    HttpEntity responseEntity = resp.getEntity();
    if (responseEntity != null) {
        Header contentType = responseEntity.getContentType();
        if (contentType != null)
            return contentType.getValue();
    }
    return null;
}
 
源代码11 项目: esigate   文件: ResponseSender.java
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());
        }
    }
}
 
源代码12 项目: BigApp_Discuz_Android   文件: URLEncodedUtils.java
/**
 * 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;
    }
}
 
@Override
public String getContentType() {
  HttpEntity entity = response.getEntity();
  if (entity != null) {
    Header contentTypeHeader = entity.getContentType();
    if (contentTypeHeader != null) {
      return contentTypeHeader.getValue();
    }
  }
  return null;
}
 
源代码14 项目: RoboZombie   文件: EntityUtils.java
/**
 * 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;
}
 
源代码15 项目: p3-batchrefine   文件: BatchRefineTransformer.java
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);
    }
}
 
源代码16 项目: RoboZombie   文件: ContentType.java
/**
 * 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;
}
 
源代码17 项目: restfiddle   文件: GenericHandler.java
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;
   }
 
源代码18 项目: ongdb-lab-apoc   文件: Dictionary.java
/**
 * 从远程服务器上下载自定义词条
 */
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;
}
 
源代码19 项目: product-emm   文件: ServerUtilities.java
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;

	}
 
源代码20 项目: gerrit-rest-java-client   文件: GerritRestClient.java
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()));
    }
}