Java Code Examples for org.apache.http.client.methods.HttpPost#getEntity()

The following examples show how to use org.apache.http.client.methods.HttpPost#getEntity() . 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: HtmlFileInput2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Helper that does some nasty magic.
 */
private static HttpEntity post(final WebClient client,
        final MockWebConnection webConnection)
        throws NoSuchMethodException, IllegalAccessException,
        InvocationTargetException {
    final Method makeHttpMethod = HttpWebConnection.class.getDeclaredMethod("makeHttpMethod",
            WebRequest.class, HttpClientBuilder.class);
    makeHttpMethod.setAccessible(true);

    final HttpWebConnection con = new HttpWebConnection(client);

    final Method getHttpClientBuilderMethod = HttpWebConnection.class.getDeclaredMethod("getHttpClientBuilder");
    getHttpClientBuilderMethod.setAccessible(true);
    final HttpClientBuilder builder = (HttpClientBuilder) getHttpClientBuilderMethod.invoke(con);

    final HttpPost httpPost = (HttpPost) makeHttpMethod.invoke(con, webConnection.getLastWebRequest(), builder);
    final HttpEntity httpEntity = httpPost.getEntity();
    return httpEntity;
}
 
Example 2
Source File: HttpTransportClient.java    From vk-java-sdk with MIT License 6 votes vote down vote up
private String getRequestPayload(HttpRequestBase request) throws IOException {
    if (!(request instanceof HttpPost)) {
        return EMPTY_PAYLOAD;
    }

    HttpPost postRequest = (HttpPost) request;
    if (postRequest.getEntity() == null) {
        return EMPTY_PAYLOAD;
    }

    if (StringUtils.isNotEmpty(postRequest.getEntity().getContentType().getValue())) {
        String contentType = postRequest.getEntity().getContentType().getValue();
        if (contentType.contains("multipart/form-data")) {
            return EMPTY_PAYLOAD;
        }
    }

    return IOUtils.toString(postRequest.getEntity().getContent(), StandardCharsets.UTF_8);
}
 
Example 3
Source File: ClusterOpenApiServiceTest.java    From apollo with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateCluster() throws Exception {
  String someCluster = "someCluster";
  String someCreatedBy = "someCreatedBy";

  OpenClusterDTO clusterDTO = new OpenClusterDTO();
  clusterDTO.setAppId(someAppId);
  clusterDTO.setName(someCluster);
  clusterDTO.setDataChangeCreatedBy(someCreatedBy);

  final ArgumentCaptor<HttpPost> request = ArgumentCaptor.forClass(HttpPost.class);

  clusterOpenApiService.createCluster(someEnv, clusterDTO);

  verify(httpClient, times(1)).execute(request.capture());

  HttpPost post = request.getValue();

  assertEquals(String
      .format("%s/envs/%s/apps/%s/clusters", someBaseUrl, someEnv, someAppId), post.getURI().toString());

  StringEntity entity = (StringEntity) post.getEntity();

  assertEquals(ContentType.APPLICATION_JSON.toString(), entity.getContentType().getValue());
  assertEquals(gson.toJson(clusterDTO), EntityUtils.toString(entity));
}
 
Example 4
Source File: MonitoringClientBuilderTest.java    From cf-java-logging-support with Apache License 2.0 6 votes vote down vote up
@Test
public void testSend() throws Exception {
    ArgumentCaptor<HttpPost> createRequestCaptor = ArgumentCaptor.forClass(HttpPost.class);
    when(httpClient.execute(createRequestCaptor.capture())).thenReturn(httpResponse);
    when(responseStatusLine.getStatusCode()).thenReturn(HttpStatus.SC_CREATED);

    client.send(metric);

    HttpPost actualPostRequest = createRequestCaptor.getValue();
    HttpEntity actualEntity = actualPostRequest.getEntity();
    String actualEntityString = EntityUtils.toString(actualEntity);
    MetricRequest actualMetricRequest = gson.fromJson(actualEntityString, MetricRequest.class);

    assertEquals(TEST_APPLICATION_GUID, actualMetricRequest.getApplicationGUID());
    assertEquals(TEST_INSTANCE_GUID, actualMetricRequest.getInstanceGUID());
    assertEquals(TEST_INSTANCE_INDEX, actualMetricRequest.getIndex());
    assertEquals(String.format(MonitoringClientImpl.REQUEST_URL_TEMPLATE, TEST_MONITORING_URL,
        TEST_APPLICATION_GUID, TEST_INSTANCE_GUID), actualPostRequest.getRequestLine().getUri());
    assertEquals("The request does not contain Authorization header", 1,
        actualPostRequest.getHeaders("Authorization").length);
}
 
Example 5
Source File: DefaultOAuth2TokenServiceTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@Test
public void executeWithAdditionalParameters_putsParametersIntoPostBody() throws IOException {
	ArgumentCaptor<HttpPost> httpPostCaptor = ArgumentCaptor.forClass(HttpPost.class);
	CloseableHttpResponse response = HttpClientTestFactory.createHttpResponse(VALID_JSON_RESPONSE);
	when(mockHttpClient.execute(any(HttpPost.class))).thenReturn(response);

	requestAccessToken(Maps.newHashMap("myKey", "myValue"));

	verify(mockHttpClient, times(1)).execute(httpPostCaptor.capture());
	HttpPost httpPost = httpPostCaptor.getValue();
	HttpEntity httpEntity = httpPost.getEntity();
	assertThat(httpEntity).isNotNull();
	String postBody = IOUtils.toString(httpEntity.getContent(), StandardCharsets.UTF_8);
	assertThat(postBody).contains("myKey=myValue");
}
 
Example 6
Source File: ApacheDefaultHttpRequestFactoryTest.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void query_parameters_moved_to_payload_for_post_request_with_no_payload
        () throws IOException, URISyntaxException {
    final Request<Object> request = newDefaultRequest(HttpMethodName.POST);
    request.withParameter("foo", "bar")
            .withParameter("alpha", "beta");
    HttpRequestBase requestBase = requestFactory.create(request, settings);
    Assert.assertThat(requestBase, Matchers.instanceOf(HttpPost
            .class));
    HttpPost post = (HttpPost) requestBase;
    HttpEntity entity = post.getEntity();
    byte[] actualContents = drainInputStream(entity.getContent());
    Assert.assertTrue(actualContents.length > 0);
}
 
Example 7
Source File: ItemOpenApiServiceTest.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateItem() throws Exception {
  String someKey = "someKey";
  String someValue = "someValue";
  String someCreatedBy = "someCreatedBy";

  OpenItemDTO itemDTO = new OpenItemDTO();
  itemDTO.setKey(someKey);
  itemDTO.setValue(someValue);
  itemDTO.setDataChangeCreatedBy(someCreatedBy);

  final ArgumentCaptor<HttpPost> request = ArgumentCaptor.forClass(HttpPost.class);

  itemOpenApiService.createItem(someAppId, someEnv, someCluster, someNamespace, itemDTO);

  verify(httpClient, times(1)).execute(request.capture());

  HttpPost post = request.getValue();

  assertEquals(String
      .format("%s/envs/%s/apps/%s/clusters/%s/namespaces/%s/items", someBaseUrl, someEnv, someAppId, someCluster,
          someNamespace), post.getURI().toString());

  StringEntity entity = (StringEntity) post.getEntity();

  assertEquals(ContentType.APPLICATION_JSON.toString(), entity.getContentType().getValue());
  assertEquals(gson.toJson(itemDTO), EntityUtils.toString(entity));
}
 
Example 8
Source File: StreamingApacheClientHttpRequestTest.java    From riptide with MIT License 5 votes vote down vote up
@Test
void shouldUseStreamingEntity() {
    final HttpClient client = mock(HttpClient.class);
    final HttpPost request = new HttpPost();

    final StreamingApacheClientHttpRequest unit = new StreamingApacheClientHttpRequest(client, request);

    unit.setBody(mock(Body.class));

    final HttpEntity entity = request.getEntity();

    assertFalse(entity.isStreaming());
    assertThrows(UnsupportedOperationException.class, entity::getContent);
    assertThrows(UnsupportedOperationException.class, entity::consumeContent);
}
 
Example 9
Source File: HttpTest.java    From Inside_Android_Testing with Apache License 2.0 5 votes vote down vote up
@Test
public void testPost_ShouldIncludePostBody() throws Exception {
    http.post("www.example.com", new HashMap<String, String>(), "a post body", null, null);

    HttpPost sentHttpRequest = (HttpPost) Robolectric.getSentHttpRequest(0);
    StringEntity entity = (StringEntity) sentHttpRequest.getEntity();
    String sentPostBody = fromStream(entity.getContent());
    assertThat(sentPostBody, equalTo("a post body"));
    assertThat(entity.getContentType().getValue(), equalTo("text/plain; charset=UTF-8"));
}
 
Example 10
Source File: HttpResponseMock.java    From iaf with Apache License 2.0 5 votes vote down vote up
public InputStream doPost(HttpHost host, HttpPost request, HttpContext context) throws IOException {
	assertEquals("POST", request.getMethod());
	StringBuilder response = new StringBuilder();
	response.append(request.toString() + lineSeparator);

	appendHeaders(request, response);

	HttpEntity entity = request.getEntity();
	if(entity instanceof MultipartEntity) {
		MultipartEntity multipartEntity = (MultipartEntity) entity;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		multipartEntity.writeTo(baos);
		String contentType = multipartEntity.getContentType().getValue();
		String boundary = getBoundary(contentType);
		contentType = contentType.replaceAll(boundary, "IGNORE");
		response.append("Content-Type: " + contentType + lineSeparator);

		response.append(lineSeparator);
		String content = new String(baos.toByteArray());
		content = content.replaceAll(boundary, "IGNORE");
		response.append(content);
	} else {
		Header contentTypeHeader = request.getEntity().getContentType();
		if(contentTypeHeader != null) {
			response.append(contentTypeHeader.getName() + ": " + contentTypeHeader.getValue() + lineSeparator);
		}

		response.append(lineSeparator);
		response.append(EntityUtils.toString(entity));
	}

	return new ByteArrayInputStream(response.toString().getBytes());
}