Java Code Examples for org.apache.http.entity.ContentType#parse()

The following examples show how to use org.apache.http.entity.ContentType#parse() . 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 File: HttpServer.java    From hsac-fitnesse-fixtures with Apache License 2.0 7 votes vote down vote up
protected Charset getCharSet(Headers heHeaders) {
    Charset charset = UTF8;
    String contentTypeHeader = heHeaders.getFirst(HTTP.CONTENT_TYPE);
    if (contentTypeHeader != null) {
        try {
            ContentType contentType = ContentType.parse(contentTypeHeader);
            Charset contentTypeCharset = contentType.getCharset();
            if (contentTypeCharset != null) {
                charset = contentTypeCharset;
            }
        } catch (ParseException | UnsupportedCharsetException e) {
            // ignore, use default charset UTF8
        }
    }
    return charset;
}
 
Example 2
Source File: MetricFetcher.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private void handleResponse(final HttpResponse response, MachineInfo machine,
                            Map<String, MetricEntity> metricMap) throws Exception {
    int code = response.getStatusLine().getStatusCode();
    if (code != HTTP_OK) {
        return;
    }
    Charset charset = null;
    try {
        String contentTypeStr = response.getFirstHeader("Content-type").getValue();
        if (StringUtil.isNotEmpty(contentTypeStr)) {
            ContentType contentType = ContentType.parse(contentTypeStr);
            charset = contentType.getCharset();
        }
    } catch (Exception ignore) {
    }
    String body = EntityUtils.toString(response.getEntity(), charset != null ? charset : DEFAULT_CHARSET);
    if (StringUtil.isEmpty(body) || body.startsWith(NO_METRICS)) {
        //logger.info(machine.getApp() + ":" + machine.getIp() + ":" + machine.getPort() + ", bodyStr is empty");
        return;
    }
    String[] lines = body.split("\n");
    //logger.info(machine.getApp() + ":" + machine.getIp() + ":" + machine.getPort() +
    //    ", bodyStr.length()=" + body.length() + ", lines=" + lines.length);
    handleBody(lines, machine, metricMap);
}
 
Example 3
Source File: MetricFetcher.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private void handleResponse(final HttpResponse response, MachineInfo machine,
                            Map<String, MetricEntity> metricMap) throws Exception {
    int code = response.getStatusLine().getStatusCode();
    if (code != HTTP_OK) {
        return;
    }
    Charset charset = null;
    try {
        String contentTypeStr = response.getFirstHeader("Content-type").getValue();
        if (StringUtil.isNotEmpty(contentTypeStr)) {
            ContentType contentType = ContentType.parse(contentTypeStr);
            charset = contentType.getCharset();
        }
    } catch (Exception ignore) {
    }
    String body = EntityUtils.toString(response.getEntity(), charset != null ? charset : DEFAULT_CHARSET);
    if (StringUtil.isEmpty(body) || body.startsWith(NO_METRICS)) {
        //logger.info(machine.getApp() + ":" + machine.getIp() + ":" + machine.getPort() + ", bodyStr is empty");
        return;
    }
    String[] lines = body.split("\n");
    //logger.info(machine.getApp() + ":" + machine.getIp() + ":" + machine.getPort() +
    //    ", bodyStr.length()=" + body.length() + ", lines=" + lines.length);
    handleBody(lines, machine, metricMap);
}
 
Example 4
Source File: MultiReadHttpServletRequestWrapper.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
private Iterable<NameValuePair> decodeParams(String body) {
    String encoding = getRequest().getCharacterEncoding();
    if (StringUtils.isEmpty(encoding)) {
        encoding = Charset.defaultCharset().name();
    }
    List<NameValuePair> params = new ArrayList<>(
            URLEncodedUtils.parse(body, Charset.forName(encoding)));
    try {
        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()), Charset.forName(encoding));
                CollectionUtils.addAll(params, postParams);
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    return params;
}
 
Example 5
Source File: HeadersBuilderTest.java    From cs-actions with Apache License 2.0 6 votes vote down vote up
@Test
public void build() {
    ContentType contentType = ContentType.parse(CONTENT_TYPE);
    List<Header> headers = new HeadersBuilder()
            .setHeaders("header1:value1\nheader2:value2")
            .setContentType(contentType)
            .buildHeaders();
    assertEquals(3, headers.size());
    assertThat(headers.get(0), instanceOf(BufferedHeader.class));
    BufferedHeader basicHeader = (BufferedHeader) headers.get(1);
    assertEquals("header2", basicHeader.getName());
    assertEquals("value2", basicHeader.getValue());
    BasicHeader contentTypeHeader = (BasicHeader) headers.get(2);
    assertEquals("Content-Type", contentTypeHeader.getName());
    assertEquals(CONTENT_TYPE, contentTypeHeader.getValue());
}
 
Example 6
Source File: Http4FileContentInfoFactory.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public FileContentInfo create(final FileContent fileContent) throws FileSystemException {
    String contentMimeType = null;
    String contentCharset = null;

    try (final Http4FileObject<Http4FileSystem> http4File = (Http4FileObject<Http4FileSystem>) FileObjectUtils
            .getAbstractFileObject(fileContent.getFile())) {
        final HttpResponse lastHeadResponse = http4File.getLastHeadResponse();

        final Header header = lastHeadResponse.getFirstHeader(HTTP.CONTENT_TYPE);

        if (header != null) {
            final ContentType contentType = ContentType.parse(header.getValue());
            contentMimeType = contentType.getMimeType();

            if (contentType.getCharset() != null) {
                contentCharset = contentType.getCharset().name();
            }
        }

        return new DefaultFileContentInfo(contentMimeType, contentCharset);
    } catch (final IOException e) {
        throw new FileSystemException(e);
    }
}
 
Example 7
Source File: EntityBuilderTest.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
@Test
public void buildEntityWithContentType() {
    ContentType parsedContentType = ContentType.parse(CONTENT_TYPE);
    HttpEntity httpEntity = entityBuilder
            .setBody("testBody")
            .setContentType(parsedContentType)
            .buildEntity();
    assertThat(httpEntity, instanceOf(StringEntity.class));
    StringEntity stringEntity = (StringEntity) httpEntity;
    assertEquals(CONTENT_TYPE, stringEntity.getContentType().getValue());
}
 
Example 8
Source File: ResponseCapturingWrapper.java    From esigate with Apache License 2.0 5 votes vote down vote up
@Override
public void setContentType(String type) {
    ContentType parsedContentType = ContentType.parse(type);
    this.contentType = parsedContentType.getMimeType();
    if (parsedContentType.getCharset() != null) {
        this.characterEncoding = parsedContentType.getCharset().name();
    }
    updateContentTypeHeader();
}
 
Example 9
Source File: HttpClient.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
/**
 * @param url URL of service
 * @param response response pre-populated with request to send. Response content and
 *          statusCode will be filled.
 * @param headers http headers to add
 * @param type contentType for request.
 */
public void delete(String url, HttpResponse response, Map<String, Object> headers, String type) {
    HttpDeleteWithBody methodPost = new HttpDeleteWithBody(url);
    ContentType contentType = ContentType.parse(type);
    HttpEntity ent = new StringEntity(response.getRequest(), contentType);
    methodPost.setEntity(ent);
    getResponse(url, response, methodPost, headers);
}
 
Example 10
Source File: EntityBuilderTest.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
@Test
public void buildEntityWithFile() throws Exception {
    ContentType parsedContentType = ContentType.parse(CONTENT_TYPE);
    final String fileName = "testFile.txt";
    PowerMockito.whenNew(File.class).withArguments(fileName).thenReturn(fileMock);
    PowerMockito.when(fileMock.exists()).thenReturn(true);

    HttpEntity httpEntity = entityBuilder
            .setFilePath(fileName)
            .setContentType(parsedContentType)
            .buildEntity();
    assertThat(httpEntity, instanceOf(FileEntity.class));
    FileEntity fileEntity = (FileEntity) httpEntity;
    assertEquals(CONTENT_TYPE, fileEntity.getContentType().getValue());
}
 
Example 11
Source File: HttpClient.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
/**
 * @param url URL of service
 * @param response response pre-populated with request to send. Response content and
 *          statusCode will be filled.
 * @param headers http headers to add
 * @param type contentType for request.
 */
public void put(String url, HttpResponse response, Map<String, Object> headers, String type) {
    HttpPut methodPut = new HttpPut(url);
    ContentType contentType = ContentType.parse(type);
    HttpEntity ent = new StringEntity(response.getRequest(), contentType);
    methodPut.setEntity(ent);
    getResponse(url, response, methodPut, headers);
}
 
Example 12
Source File: HttpClient.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
/**
 * @param url URL of service
 * @param response response pre-populated with request to send. Response content and
 *          statusCode will be filled.
 * @param headers http headers to add
 * @param type contentType for request.
 */
public void post(String url, HttpResponse response, Map<String, Object> headers, String type) {
    HttpPost methodPost = new HttpPost(url);
    ContentType contentType = ContentType.parse(type);
    HttpEntity ent = new StringEntity(response.getRequest(), contentType);
    methodPost.setEntity(ent);
    getResponse(url, response, methodPost, headers);
}
 
Example 13
Source File: ApacheHttpClient.java    From feign with Apache License 2.0 5 votes vote down vote up
private ContentType getContentType(Request request) {
  ContentType contentType = null;
  for (Map.Entry<String, Collection<String>> entry : request.headers().entrySet())
    if (entry.getKey().equalsIgnoreCase("Content-Type")) {
      Collection<String> values = entry.getValue();
      if (values != null && !values.isEmpty()) {
        contentType = ContentType.parse(values.iterator().next());
        if (contentType.getCharset() == null) {
          contentType = contentType.withCharset(request.charset());
        }
        break;
      }
    }
  return contentType;
}
 
Example 14
Source File: RDF4JProtocolSession.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void upload(InputStream contents, String baseURI, RDFFormat dataFormat, boolean overwrite,
		boolean preserveNodeIds, Action action, Resource... contexts)
		throws IOException, RDFParseException, RepositoryException, UnauthorizedException {
	// Set Content-Length to -1 as we don't know it and we also don't want to
	// cache
	HttpEntity entity = new InputStreamEntity(contents, -1, ContentType.parse(dataFormat.getDefaultMIMEType()));
	upload(entity, baseURI, overwrite, preserveNodeIds, action, contexts);
}
 
Example 15
Source File: HttpSender.java    From iaf with Apache License 2.0 5 votes vote down vote up
public static String handleMultipartResponse(String mimeType, InputStream inputStream, IPipeLineSession session, HttpResponseHandler httpHandler) throws IOException, SenderException {
	String result = null;
	try {
		InputStreamDataSource dataSource = new InputStreamDataSource(mimeType, inputStream);
		MimeMultipart mimeMultipart = new MimeMultipart(dataSource);
		for (int i = 0; i < mimeMultipart.getCount(); i++) {
			BodyPart bodyPart = mimeMultipart.getBodyPart(i);
			boolean lastPart = mimeMultipart.getCount() == i + 1;
			if (i == 0) {
				String charset = Misc.DEFAULT_INPUT_STREAM_ENCODING;
				ContentType contentType = ContentType.parse(bodyPart.getContentType());
				if(contentType.getCharset() != null)
					charset = contentType.getCharset().name();

				InputStream bodyPartInputStream = bodyPart.getInputStream();
				result = Misc.streamToString(bodyPartInputStream, charset);
				if (lastPart) {
					bodyPartInputStream.close();
				}
			} else {
				// When the last stream is read the
				// httpMethod.releaseConnection() can be called, hence pass
				// httpMethod to ReleaseConnectionAfterReadInputStream.
				session.put("multipart" + i, new ReleaseConnectionAfterReadInputStream( lastPart ? httpHandler : null, bodyPart.getInputStream()));
			}
		}
	} catch(MessagingException e) {
		throw new SenderException("Could not read mime multipart response", e);
	}
	return result;
}
 
Example 16
Source File: SentinelApiClient.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private String getBody(HttpResponse response) throws Exception {
    Charset charset = null;
    try {
        String contentTypeStr = response.getFirstHeader(HTTP_HEADER_CONTENT_TYPE).getValue();
        if (StringUtil.isNotEmpty(contentTypeStr)) {
            ContentType contentType = ContentType.parse(contentTypeStr);
            charset = contentType.getCharset();
        }
    } catch (Exception ignore) {
    }
    return EntityUtils.toString(response.getEntity(), charset != null ? charset : DEFAULT_CHARSET);
}
 
Example 17
Source File: SentinelApiClient.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private String getBody(HttpResponse response) throws Exception {
    Charset charset = null;
    try {
        String contentTypeStr = response.getFirstHeader("Content-type").getValue();
        if (StringUtil.isNotEmpty(contentTypeStr)) {
            ContentType contentType = ContentType.parse(contentTypeStr);
            charset = contentType.getCharset();
        }
    } catch (Exception ignore) {
    }
    return EntityUtils.toString(response.getEntity(), charset != null ? charset : DEFAULT_CHARSET);
}
 
Example 18
Source File: UrlRewriteRequestTest.java    From knox with Apache License 2.0 4 votes vote down vote up
@Test
public void testEmptyPayload() throws Exception {
  /* copy results */
  final ByteArrayOutputStream results = new ByteArrayOutputStream();
  final ByteArrayInputStream bai = new ByteArrayInputStream(
      "".getBytes(StandardCharsets.UTF_8));

  final ServletInputStream payload = new ServletInputStream() {

    @Override
    public int read() {
      return bai.read();
    }

    @Override
    public int available() {
      return bai.available();
    }

    @Override
    public boolean isFinished() {
      return false;
    }

    @Override
    public boolean isReady() {
      return false;
    }

    @Override
    public void setReadListener(ReadListener readListener) {
    }
  };

  UrlRewriteProcessor rewriter = EasyMock.createNiceMock(UrlRewriteProcessor.class);

  ServletContext context = EasyMock.createNiceMock(ServletContext.class);
  EasyMock.expect(context.getServletContextName())
      .andReturn("test-cluster-name").anyTimes();
  EasyMock.expect(context.getInitParameter("test-init-param-name"))
      .andReturn("test-init-param-value").anyTimes();
  EasyMock.expect(context.getAttribute(
      UrlRewriteServletContextListener.PROCESSOR_ATTRIBUTE_NAME))
      .andReturn(rewriter).anyTimes();

  FilterConfig config = EasyMock.createNiceMock(FilterConfig.class);
  EasyMock.expect(config.getInitParameter("test-filter-init-param-name"))
      .andReturn("test-filter-init-param-value").anyTimes();
  EasyMock.expect(config.getServletContext()).andReturn(context).anyTimes();

  HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
  EasyMock.expect(request.getScheme()).andReturn("https").anyTimes();
  EasyMock.expect(request.getServerName()).andReturn("targethost.com").anyTimes();
  EasyMock.expect(request.getServerPort()).andReturn(80).anyTimes();
  EasyMock.expect(request.getRequestURI()).andReturn("/").anyTimes();
  EasyMock.expect(request.getQueryString()).andReturn(null).anyTimes();
  EasyMock.expect(request.getHeader("Host")).andReturn("sourcehost.com").anyTimes();

  EasyMock.expect(request.getMethod()).andReturn("POST").anyTimes();
  EasyMock.expect(request.getContentType()).andReturn("application/xml").anyTimes();
  EasyMock.expect(request.getInputStream()).andReturn(payload).anyTimes();
  EasyMock.expect(request.getContentLength()).andReturn(-1).anyTimes();

  HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
  EasyMock.replay(rewriter, context, config, request, response);

  // instantiate UrlRewriteRequest so that we can use it as a Template factory for targetUrl
  UrlRewriteRequest rewriteRequest = new UrlRewriteRequest(config, request);

  ServletInputStream inputStream = rewriteRequest.getInputStream();
  HttpEntity entity = new InputStreamEntity(inputStream,
      request.getContentLength(), ContentType.parse("application/xml"));
  entity.writeTo(results);

}
 
Example 19
Source File: ContentTypeTests.java    From hsac-fitnesse-fixtures with Apache License 2.0 4 votes vote down vote up
@Test
public void testXMLParse() {
    ContentType contentType = ContentType.parse(XmlHttpResponse.CONTENT_TYPE_XML_TEXT_UTF8);
    assertEquals(Charset.forName("UTF-8"), contentType.getCharset());
    assertEquals(ContentType.TEXT_XML.getMimeType(), contentType.getMimeType());
}
 
Example 20
Source File: ContentTypeTests.java    From hsac-fitnesse-fixtures with Apache License 2.0 4 votes vote down vote up
@Test
public void testFormEncodedParse() {
    ContentType contentType = ContentType.parse(HttpTest.DEFAULT_POST_CONTENT_TYPE);
    assertEquals(Charset.forName("UTF-8"), contentType.getCharset());
    assertEquals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType(), contentType.getMimeType());
}