org.apache.http.HttpEntity.getContentType()方法的使用及代码示例

x33g5p2x  于2022-01-19 转载在 其他  
字(11.7k)|赞(0)|评价(0)|浏览(341)

本文整理了Java中org.apache.http.HttpEntity.getContentType()方法的一些代码示例,展示了HttpEntity.getContentType()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpEntity.getContentType()方法的具体详情如下:
包路径:org.apache.http.HttpEntity
类名称:HttpEntity
方法名:getContentType

HttpEntity.getContentType介绍

[英]Obtains the Content-Type header, if known. This is the header that should be used when sending the entity, or the one that was received with the entity. It can include a charset attribute.
[中]获取内容类型标头(如果已知)。这是发送实体时应使用的标头,或随实体一起接收的标头。它可以包含一个字符集属性。

代码示例

代码示例来源:origin: square/okhttp

HttpEntityBody(HttpEntity entity, String contentTypeHeader) {
 this.entity = entity;
 if (contentTypeHeader != null) {
  mediaType = MediaType.parse(contentTypeHeader);
 } else if (entity.getContentType() != null) {
  mediaType = MediaType.parse(entity.getContentType().getValue());
 } else {
  // Apache is forgiving and lets you skip specifying a content type with an entity. OkHttp is
  // not forgiving so we fall back to a generic type if it's missing.
  mediaType = DEFAULT_MEDIA_TYPE;
 }
}

代码示例来源:origin: robovm/robovm

public Header getContentType() {
  return wrappedEntity.getContentType();
}

代码示例来源:origin: robovm/robovm

/**
 * Returns true if the entity's Content-Type header is
 * <code>application/x-www-form-urlencoded</code>.
 */
public static boolean isEncoded (final HttpEntity entity) {
  final Header contentType = entity.getContentType();
  return (contentType != null && contentType.getValue().equalsIgnoreCase(CONTENT_TYPE));
}

代码示例来源:origin: apache/geode

public HttpResponseAssert hasContentType(String contentType) {
 assertThat(actual.getEntity().getContentType().getValue()).containsIgnoringCase(contentType);
 return this;
}

代码示例来源:origin: robovm/robovm

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;
}

代码示例来源:origin: medcl/elasticsearch-analysis-ik

if (response.getEntity().getContentType().getValue().contains("charset=")) {
  String contentType = response.getEntity().getContentType().getValue();
  charset = contentType.substring(contentType.lastIndexOf("=") + 1);

代码示例来源:origin: sarxos/webcam-capture

private InputStream get(final URI uri, boolean withoutImageMime) throws UnsupportedOperationException, IOException {
  final HttpGet get = new HttpGet(uri);
  final HttpResponse respone = client.execute(get, context);
  final HttpEntity entity = respone.getEntity();
  // normal jpeg return image/jpeg as opposite to mjpeg
  if (withoutImageMime) {
    final Header contentType = entity.getContentType();
    if (contentType == null) {
      throw new WebcamException("Content Type header is missing");
    }
    if (contentType.getValue().startsWith("image/")) {
      throw new WebcamException("Cannot read images in PUSH mode, change mode to PULL " + contentType);
    }
  }
  return entity.getContent();
}

代码示例来源:origin: mttkay/ignition

HttpPost(IgnitedHttp ignitedHttp, String url, HttpEntity payload,
    HashMap<String, String> defaultHeaders) {
  super(ignitedHttp);
  this.request = new org.apache.http.client.methods.HttpPost(url);
  ((HttpEntityEnclosingRequest) request).setEntity(payload);
  request.setHeader(HTTP_CONTENT_TYPE_HEADER, payload.getContentType().getValue());
  for (String header : defaultHeaders.keySet()) {
    request.setHeader(header, defaultHeaders.get(header));
  }
}

代码示例来源:origin: mttkay/ignition

HttpPut(IgnitedHttp ignitedHttp, String url, HttpEntity payload,
    HashMap<String, String> defaultHeaders) {
  super(ignitedHttp);
  this.request = new org.apache.http.client.methods.HttpPut(url);
  ((HttpEntityEnclosingRequest) request).setEntity(payload);
  request.setHeader(HTTP_CONTENT_TYPE_HEADER, payload.getContentType().getValue());
  for (String header : defaultHeaders.keySet()) {
    request.setHeader(header, defaultHeaders.get(header));
  }
}

代码示例来源:origin: alibaba/nacos

public static HttpResult httpPostLarge(String url, Map<String, String> headers, String content) {
  try {
    HttpClientBuilder builder = HttpClients.custom();
    builder.setUserAgent(UtilsAndCommons.SERVER_VERSION);
    builder.setConnectionTimeToLive(500, TimeUnit.MILLISECONDS);
    CloseableHttpClient httpClient = builder.build();
    HttpPost httpost = new HttpPost(url);
    for (Map.Entry<String, String> entry : headers.entrySet()) {
      httpost.setHeader(entry.getKey(), entry.getValue());
    }
    httpost.setEntity(new StringEntity(content, ContentType.create("application/json", "UTF-8")));
    HttpResponse response = httpClient.execute(httpost);
    HttpEntity entity = response.getEntity();
    HeaderElement[] headerElements = entity.getContentType().getElements();
    String charset = headerElements[0].getParameterByName("charset").getValue();
    return new HttpResult(response.getStatusLine().getStatusCode(),
        IOUtils.toString(entity.getContent(), charset), Collections.<String, String>emptyMap());
  } catch (Exception e) {
    return new HttpResult(500, e.toString(), Collections.<String, String>emptyMap());
  }
}

代码示例来源:origin: alibaba/nacos

public static HttpResult httpPost(String url, List<String> headers, Map<String, String> paramValues, String encoding) {
  try {
    HttpPost httpost = new HttpPost(url);
    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(5000).setSocketTimeout(5000).setRedirectsEnabled(true).setMaxRedirects(5).build();
    httpost.setConfig(requestConfig);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    for (Map.Entry<String, String> entry : paramValues.entrySet()) {
      nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }
    httpost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
    HttpResponse response = postClient.execute(httpost);
    HttpEntity entity = response.getEntity();
    String charset = encoding;
    if (entity.getContentType() != null) {
      HeaderElement[] headerElements = entity.getContentType().getElements();
      if (headerElements != null && headerElements.length > 0 && headerElements[0] != null &&
          headerElements[0].getParameterByName("charset") != null) {
        charset = headerElements[0].getParameterByName("charset").getValue();
      }
    }
    return new HttpResult(response.getStatusLine().getStatusCode(), IOUtils.toString(entity.getContent(), charset), Collections.<String, String>emptyMap());
  } catch (Throwable e) {
    return new HttpResult(500, e.toString(), Collections.<String, String>emptyMap());
  }
}

代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server

@Override
public CachedImage load(ClientDetailsEntity key) throws Exception {
  try {
    HttpResponse response = httpClient.execute(new HttpGet(key.getLogoUri()));
    HttpEntity entity = response.getEntity();
    CachedImage image = new CachedImage();
    image.setContentType(entity.getContentType().getValue());
    image.setLength(entity.getContentLength());
    image.setData(IOUtils.toByteArray(entity.getContent()));
    return image;
  } catch (IOException e) {
    throw new IllegalArgumentException("Unable to load client image.");
  }
}

代码示例来源:origin: code4craft/webmagic

protected Page handleResponse(Request request, String charset, HttpResponse httpResponse, Task task) throws IOException {
  byte[] bytes = IOUtils.toByteArray(httpResponse.getEntity().getContent());
  String contentType = httpResponse.getEntity().getContentType() == null ? "" : httpResponse.getEntity().getContentType().getValue();
  Page page = new Page();
  page.setBytes(bytes);
  if (!request.isBinaryContent()){
    if (charset == null) {
      charset = getHtmlCharset(contentType, bytes);
    }
    page.setCharset(charset);
    page.setRawText(new String(bytes, charset));
  }
  page.setUrl(new PlainText(request.getUrl()));
  page.setRequest(request);
  page.setStatusCode(httpResponse.getStatusLine().getStatusCode());
  page.setDownloadSuccess(true);
  if (responseHeader) {
    page.setHeaders(HttpClientUtils.convertHeaders(httpResponse.getAllHeaders()));
  }
  return page;
}

代码示例来源:origin: apache/incubator-gobblin

@Override
public ApacheHttpResponseStatus handleResponse(Request<HttpUriRequest> request, RP response) {
 ApacheHttpResponseStatus status = new ApacheHttpResponseStatus(StatusType.OK);
 int statusCode = response.getStatusLine().getStatusCode();
 status.setStatusCode(statusCode);
 HttpUtils.updateStatusType(status, statusCode, errorCodeWhitelist);
 if (status.getType() == StatusType.OK) {
  status.setContent(getEntityAsByteArray(response.getEntity()));
  status.setContentType(response.getEntity().getContentType().getValue());
 } else {
  log.info("Receive an unsuccessful response with status code: " + statusCode);
 }
 HttpEntity entity = response.getEntity();
 if (entity != null) {
  consumeEntity(entity);
 }
 return status;
}

代码示例来源:origin: dreamhead/moco

private HttpEntity checkJsonResponse(final HttpResponse response) {
  assertThat(response.getStatusLine().getStatusCode(), is(200));
  HttpEntity entity = response.getEntity();
  MediaType mediaType = MediaType.parse(entity.getContentType().getValue());
  assertThat(mediaType.type(), is("application"));
  assertThat(mediaType.subtype(), is("json"));
  return entity;
}

代码示例来源:origin: dreamhead/moco

private void assertJson(final String url, final String content) throws IOException {
    HttpResponse response = helper.getResponse(url);
    HttpEntity entity = response.getEntity();
    byte[] bytes = ByteStreams.toByteArray(entity.getContent());
    assertThat(new String(bytes), is(content));
    MediaType mediaType = MediaType.parse(entity.getContentType().getValue());
    assertThat(mediaType.type(), is("application"));
    assertThat(mediaType.subtype(), is("json"));
  }
}

代码示例来源:origin: dreamhead/moco

private Plain asPlain(org.apache.http.HttpResponse response) throws IOException {
  assertThat(response.getStatusLine().getStatusCode(), is(200));
  HttpEntity entity = response.getEntity();
  MediaType mediaType = MediaType.parse(entity.getContentType().getValue());
  assertThat(mediaType.type(), is("application"));
  assertThat(mediaType.subtype(), is("json"));
  return Jsons.toObject(entity.getContent(), Plain.class);
}

代码示例来源:origin: dreamhead/moco

private void assertJson(final String url, final String content) throws IOException {
    HttpResponse response = helper.getResponse(url);
    HttpEntity entity = response.getEntity();
    byte[] bytes = ByteStreams.toByteArray(entity.getContent());
    assertThat(new String(bytes), is(content));
    MediaType mediaType = MediaType.parse(entity.getContentType().getValue());
    assertThat(mediaType.type(), is("application"));
    assertThat(mediaType.subtype(), is("json"));
  }
}

代码示例来源:origin: dreamhead/moco

public static void assertEquals(final String expected, final HttpResponse response) {
  HttpEntity entity = response.getEntity();
  MediaType mediaType = MediaType.parse(entity.getContentType().getValue());
  assertThat(mediaType.type(), is("application"));
  assertThat(mediaType.subtype(), is("json"));
  try {
    JSONAssert.assertEquals(expected,
        EntityUtils.toString(entity), JSONCompareMode.LENIENT);
  } catch (JSONException | IOException e) {
    throw new AssertionError("fail to parse entity to json");
  }
}

代码示例来源:origin: confluentinc/ksql

@Test
 public void testHandle() throws IOException {
  final HttpResponse response = mock(HttpResponse.class);
  final StatusLine statusLine = mock(StatusLine.class);
  final HttpEntity entity = mock(HttpEntity.class);
  final Logger log = mock(Logger.class);
  final Header header = mock(Header.class);
  expect(response.getStatusLine()).andReturn(statusLine).once();
  expect(statusLine.getStatusCode()).andReturn(HttpStatus.SC_OK).once();
  expect(response.getEntity()).andReturn(entity).times(2);
  final ByteArrayInputStream bais = new ByteArrayInputStream("yolo".getBytes(StandardCharsets.UTF_8));
  expect(entity.getContent()).andReturn(bais).times(2);
  expect(entity.getContentType()).andReturn(header).times(1);
  expect(header.getElements()).andReturn(new HeaderElement[]{});
  expect(entity.getContentLength()).andReturn(4L).times(2);
  log.warn("yolo");
  expectLastCall().once();
  replay(response, statusLine, entity, header, log);
  final KsqlVersionCheckerResponseHandler kvcr = new KsqlVersionCheckerResponseHandler(log);
  kvcr.handle(response);
  verify(response, statusLine, entity, header, log);
 }
}

相关文章