org.apache.http.client.methods.HttpPost#getEntity()源码实例Demo

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

源代码1 项目: htmlunit   文件: HtmlFileInput2Test.java
/**
 * 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;
}
 
源代码2 项目: vk-java-sdk   文件: HttpTransportClient.java
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);
}
 
源代码3 项目: apollo   文件: ClusterOpenApiServiceTest.java
@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));
}
 
@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);
}
 
@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");
}
 
@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);
}
 
源代码7 项目: apollo   文件: ItemOpenApiServiceTest.java
@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));
}
 
@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);
}
 
源代码9 项目: Inside_Android_Testing   文件: HttpTest.java
@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"));
}
 
源代码10 项目: iaf   文件: HttpResponseMock.java
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());
}