Java Code Examples for org.apache.http.entity.InputStreamEntity

The following are top voted examples for showing how to use org.apache.http.entity.InputStreamEntity. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: OkApacheClient.java   View source code 6 votes vote down vote up
private static HttpResponse transformResponse(Response response) {
  int code = response.code();
  String message = response.message();
  BasicHttpResponse httpResponse = new BasicHttpResponse(HTTP_1_1, code, message);

  ResponseBody body = response.body();
  InputStreamEntity entity = new InputStreamEntity(body.byteStream(), body.contentLength());
  httpResponse.setEntity(entity);

  Headers headers = response.headers();
  for (int i = 0, size = headers.size(); i < size; i++) {
    String name = headers.name(i);
    String value = headers.value(i);
    httpResponse.addHeader(name, value);
    if ("Content-Type".equalsIgnoreCase(name)) {
      entity.setContentType(value);
    } else if ("Content-Encoding".equalsIgnoreCase(name)) {
      entity.setContentEncoding(value);
    }
  }

  return httpResponse;
}
 
Example 2
Project: GitHub   File: OkApacheClient.java   View source code 6 votes vote down vote up
private static HttpResponse transformResponse(Response response) {
  int code = response.code();
  String message = response.message();
  BasicHttpResponse httpResponse = new BasicHttpResponse(HTTP_1_1, code, message);

  ResponseBody body = response.body();
  InputStreamEntity entity = new InputStreamEntity(body.byteStream(), body.contentLength());
  httpResponse.setEntity(entity);

  Headers headers = response.headers();
  for (int i = 0, size = headers.size(); i < size; i++) {
    String name = headers.name(i);
    String value = headers.value(i);
    httpResponse.addHeader(name, value);
    if ("Content-Type".equalsIgnoreCase(name)) {
      entity.setContentType(value);
    } else if ("Content-Encoding".equalsIgnoreCase(name)) {
      entity.setContentEncoding(value);
    }
  }

  return httpResponse;
}
 
Example 3
Project: GitHub   File: OkApacheClientTest.java   View source code 6 votes vote down vote up
@Test public void postInputStreamEntity() throws Exception {
  server.enqueue(new MockResponse());

  final HttpPost post = new HttpPost(server.url("/").url().toURI());
  byte[] body = "Hello, world!".getBytes(UTF_8);
  post.setEntity(new InputStreamEntity(new ByteArrayInputStream(body), body.length));
  client.execute(post);

  RecordedRequest request = server.takeRequest();
  assertEquals("Hello, world!", request.getBody().readUtf8());
  assertEquals(request.getHeader("Content-Length"), "13");
}
 
Example 4
Project: act-platform   File: FactSearchManager.java   View source code 6 votes vote down vote up
private void createIndex() {
  Response response;

  try (InputStream payload = FactSearchManager.class.getClassLoader().getResourceAsStream(MAPPINGS_JSON)) {
    // Need to use low-level client here because the Index API is not yet supported by the high-level client.
    HttpEntity body = new InputStreamEntity(payload, ContentType.APPLICATION_JSON);
    response = clientFactory.getLowLevelClient().performRequest("PUT", INDEX_NAME, Collections.emptyMap(), body);
  } catch (IOException ex) {
    throw logAndExit(ex, "Could not perform request to create index.");
  }

  if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
    String msg = String.format("Could not create index '%s'.", INDEX_NAME);
    LOGGER.error(msg);
    throw new IllegalStateException(msg);
  }

  LOGGER.info("Successfully created index '%s'.", INDEX_NAME);
}
 
Example 5
Project: datarouter   File: CachingHttpServletRequest.java   View source code 6 votes vote down vote up
public byte[] getContent() throws IOException{
	if(content != null){
		return content;
	}

	// don't close stream
	content = EntityUtils.toByteArray(new InputStreamEntity(super.getInputStream()));
	return content;
}
 
Example 6
Project: datarouter   File: CachingHttpServletRequestTests.java   View source code 6 votes vote down vote up
@Test
public void test() throws IOException{
	String sentBody = "{ 'key': 'value' }";
	Charset charset = StandardCharsets.UTF_8;
	StringEntity sentEntity = new StringEntity(sentBody, charset);
	HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
	Mockito.doAnswer(any -> new CachingServletInputStream(sentEntity.getContent()))
			.when(request).getInputStream();

	CachingHttpServletRequest cachingRequest = CachingHttpServletRequest.getOrCreate(request);
	// test repeat reads
	for(int i = 0; i < 5; i++){
		InputStreamEntity entity = new InputStreamEntity(request.getInputStream());
		String receivedBody = EntityUtils.toString(entity, charset);
		Assert.assertEquals(sentBody, receivedBody);

		receivedBody = EntityUtils.toString(new InputStreamEntity(cachingRequest.getInputStream()), charset);
		Assert.assertEquals(sentBody, receivedBody);
	}

	Assert.assertSame(CachingHttpServletRequest.getOrCreate(cachingRequest), cachingRequest);
}
 
Example 7
Project: delivery-sdk-java   File: DocsExamplesTest.java   View source code 6 votes vote down vote up
@Test
public void testRetrievingContentInSpecificLanguage() throws Exception {
    String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c";

    this.serverBootstrap.registerHandler(
            String.format("/%s/%s", projectId, "items/on_roasts"),
            (request, response, context) -> response.setEntity(
                    new InputStreamEntity(
                            this.getClass().getResourceAsStream("DocsExamplesRetrievingContentInSpecificLanguage.json")
                    )
            ));
    HttpHost httpHost = this.start();
    DeliveryClient client = new DeliveryClient(projectId);

    //modify default baseurl to point to test server, this is private so using reflection
    String testServerUri = httpHost.toURI() + "/%s";
    Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions");
    deliveryOptionsField.setAccessible(true);
    ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri);

    List<NameValuePair> params = DeliveryParameterBuilder.params().language("es-ES").build();

    ArticleItem item = client.getItem("on_roasts", ArticleItem.class, params);
    Assert.assertNotNull(item);
}
 
Example 8
Project: delivery-sdk-java   File: DocsExamplesTest.java   View source code 6 votes vote down vote up
@Test
public void testViewContentItem() throws Exception {
    String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c";

    this.serverBootstrap.registerHandler(
            String.format("/%s/%s", projectId, "items/on_roasts"),
            (request, response, context) -> response.setEntity(
                    new InputStreamEntity(
                            this.getClass().getResourceAsStream("SampleContentItem.json")
                    )
            ));
    HttpHost httpHost = this.start();
    DeliveryClient client = new DeliveryClient(projectId);

    //modify default baseurl to point to test server, this is private so using reflection
    String testServerUri = httpHost.toURI() + "/%s";
    Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions");
    deliveryOptionsField.setAccessible(true);
    ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri);

    List<NameValuePair> params = DeliveryParameterBuilder.params().projection("title", "summary", "post_date", "teaser_image", "related_articles").build();

    ArticleItem item = client.getItem("on_roasts", ArticleItem.class, params);
    Assert.assertNotNull(item);
}
 
Example 9
Project: delivery-sdk-java   File: DocsExamplesTest.java   View source code 6 votes vote down vote up
@Test
public void testListContentTypes() throws Exception {
    String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c";

    this.serverBootstrap.registerHandler(
            String.format("/%s/%s", projectId, "types"),
            (request, response, context) -> response.setEntity(
                    new InputStreamEntity(
                            this.getClass().getResourceAsStream("SampleContentTypeList.json")
                    )
            ));
    HttpHost httpHost = this.start();
    DeliveryClient client = new DeliveryClient(projectId);

    //modify default baseurl to point to test server, this is private so using reflection
    String testServerUri = httpHost.toURI() + "/%s";
    Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions");
    deliveryOptionsField.setAccessible(true);
    ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri);

    List<NameValuePair> params = DeliveryParameterBuilder.params().page(null, 3).build();
    ContentTypesListingResponse types = client.getTypes(params);

    Assert.assertNotNull(types);
}
 
Example 10
Project: delivery-sdk-java   File: DocsExamplesTest.java   View source code 6 votes vote down vote up
@Test
public void testViewContentType() throws Exception {
    String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c";

    this.serverBootstrap.registerHandler(
            String.format("/%s/%s", projectId, "types/coffee"),
            (request, response, context) -> response.setEntity(
                    new InputStreamEntity(
                            this.getClass().getResourceAsStream("SampleContentType.json")
                    )
            ));
    HttpHost httpHost = this.start();
    DeliveryClient client = new DeliveryClient(projectId);

    //modify default baseurl to point to test server, this is private so using reflection
    String testServerUri = httpHost.toURI() + "/%s";
    Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions");
    deliveryOptionsField.setAccessible(true);
    ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri);

    ContentType type = client.getType("coffee");
    Assert.assertNotNull(type);
}
 
Example 11
Project: delivery-sdk-java   File: DocsExamplesTest.java   View source code 6 votes vote down vote up
@Test
public void testViewContentTypeElement() throws Exception {
    String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c";

    this.serverBootstrap.registerHandler(
            String.format("/%s/%s", projectId, "types/coffee/elements/processing"),
            (request, response, context) -> response.setEntity(
                    new InputStreamEntity(
                            this.getClass().getResourceAsStream("SampleContentTypeElementResponse.json")
                    )
            ));
    HttpHost httpHost = this.start();
    DeliveryClient client = new DeliveryClient(projectId);

    //modify default baseurl to point to test server, this is private so using reflection
    String testServerUri = httpHost.toURI() + "/%s";
    Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions");
    deliveryOptionsField.setAccessible(true);
    ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri);

    Element element = client.getContentTypeElement("coffee", "processing");
    Assert.assertNotNull(element);
    Assert.assertEquals("processing", element.getCodeName());
    Assert.assertTrue(element instanceof MultipleChoiceElement);
}
 
Example 12
Project: delivery-sdk-java   File: DocsExamplesTest.java   View source code 6 votes vote down vote up
@Test
public void testViewTaxonomyGroup() throws Exception {
    String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c";

    this.serverBootstrap.registerHandler(
            String.format("/%s/%s", projectId, "taxonomies/personas"),
            (request, response, context) -> response.setEntity(
                    new InputStreamEntity(
                            this.getClass().getResourceAsStream("SampleTaxonomyGroup.json")
                    )
            ));
    HttpHost httpHost = this.start();
    DeliveryClient client = new DeliveryClient(projectId);

    //modify default baseurl to point to test server, this is private so using reflection
    String testServerUri = httpHost.toURI() + "/%s";
    Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions");
    deliveryOptionsField.setAccessible(true);
    ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri);

    TaxonomyGroup taxonomyGroup = client.getTaxonomyGroup("personas");
    Assert.assertNotNull(taxonomyGroup);
}
 
Example 13
Project: delivery-sdk-java   File: DeliveryClientTest.java   View source code 6 votes vote down vote up
@Test
public void testGetAllItems() throws Exception {
    String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c";

    this.serverBootstrap.registerHandler(
            String.format("/%s/%s", projectId, "items"),
            (request, response, context) -> response.setEntity(
                    new InputStreamEntity(
                            this.getClass().getResourceAsStream("SampleContentItemList.json")
                    )
            ));
    HttpHost httpHost = this.start();

    DeliveryOptions deliveryOptions = new DeliveryOptions();
    deliveryOptions.setProductionEndpoint(httpHost.toURI() + "/%s");
    deliveryOptions.setProjectId(projectId);
    DeliveryClient client = new DeliveryClient(deliveryOptions, null);

    ContentItemsListingResponse items = client.getItems();
    Assert.assertNotNull(items);
}
 
Example 14
Project: delivery-sdk-java   File: DeliveryClientTest.java   View source code 6 votes vote down vote up
@Test
public void testGetItem() throws Exception {
    String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c";

    this.serverBootstrap.registerHandler(
            String.format("/%s/%s", projectId, "items/on_roasts"),
            (request, response, context) -> response.setEntity(
                    new InputStreamEntity(
                            this.getClass().getResourceAsStream("SampleContentItem.json")
                    )
            ));
    HttpHost httpHost = this.start();
    DeliveryClient client = new DeliveryClient(projectId);

    //modify default baseurl to point to test server, this is private so using reflection
    String testServerUri = httpHost.toURI() + "/%s";
    Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions");
    deliveryOptionsField.setAccessible(true);
    ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri);

    ContentItemResponse item = client.getItem("on_roasts");
    Assert.assertNotNull(item);
}
 
Example 15
Project: delivery-sdk-java   File: DeliveryClientTest.java   View source code 6 votes vote down vote up
@Test
public void testGetTaxonomyGroup() throws Exception {
    String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c";

    this.serverBootstrap.registerHandler(
            String.format("/%s/%s", projectId, "taxonomies/personas"),
            (request, response, context) -> response.setEntity(
                    new InputStreamEntity(
                            this.getClass().getResourceAsStream("SampleTaxonomyGroup.json")
                    )
            ));
    HttpHost httpHost = this.start();
    DeliveryClient client = new DeliveryClient(projectId);

    //modify default baseurl to point to test server, this is private so using reflection
    String testServerUri = httpHost.toURI() + "/%s";
    Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions");
    deliveryOptionsField.setAccessible(true);
    ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri);

    TaxonomyGroup taxonomyGroup = client.getTaxonomyGroup("personas");
    Assert.assertNotNull(taxonomyGroup);
}
 
Example 16
Project: delivery-sdk-java   File: DeliveryClientTest.java   View source code 6 votes vote down vote up
@Test
public void testGetStronglyTypedItemByRegisteringType() throws Exception {
    String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c";

    this.serverBootstrap.registerHandler(
            String.format("/%s/%s", projectId, "items/on_roasts"),
            (request, response, context) -> response.setEntity(
                    new InputStreamEntity(
                            this.getClass().getResourceAsStream("SampleContentItem.json")
                    )
            ));
    HttpHost httpHost = this.start();
    DeliveryClient client = new DeliveryClient(projectId);
    client.registerType("article", ArticleItem.class);

    //modify default baseurl to point to test server, this is private so using reflection
    String testServerUri = httpHost.toURI() + "/%s";
    Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions");
    deliveryOptionsField.setAccessible(true);
    ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri);

    Object itemObj = client.getItem("on_roasts", Object.class);
    Assert.assertNotNull(itemObj);
    Assert.assertTrue(itemObj instanceof ArticleItem);
}
 
Example 17
Project: delivery-sdk-java   File: DeliveryClientTest.java   View source code 6 votes vote down vote up
@Test
public void testGetStronglyTypedItemByRegisteringMapping() throws Exception {
    String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c";

    this.serverBootstrap.registerHandler(
            String.format("/%s/%s", projectId, "items/on_roasts"),
            (request, response, context) -> response.setEntity(
                    new InputStreamEntity(
                            this.getClass().getResourceAsStream("SampleContentItem.json")
                    )
            ));
    HttpHost httpHost = this.start();
    DeliveryClient client = new DeliveryClient(projectId);
    client.registerType(ArticleItem.class);

    //modify default baseurl to point to test server, this is private so using reflection
    String testServerUri = httpHost.toURI() + "/%s";
    Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions");
    deliveryOptionsField.setAccessible(true);
    ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri);

    Object itemObj = client.getItem("on_roasts", Object.class);
    Assert.assertNotNull(itemObj);
    Assert.assertTrue(itemObj instanceof ArticleItem);
}
 
Example 18
Project: delivery-sdk-java   File: DeliveryClientTest.java   View source code 6 votes vote down vote up
@Test
public void testGetStronglyTypedItemByClasspathScan() throws Exception {
    String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c";

    this.serverBootstrap.registerHandler(
            String.format("/%s/%s", projectId, "items/on_roasts"),
            (request, response, context) -> response.setEntity(
                    new InputStreamEntity(
                            this.getClass().getResourceAsStream("SampleContentItem.json")
                    )
            ));
    HttpHost httpHost = this.start();
    DeliveryClient client = new DeliveryClient(projectId);
    client.scanClasspathForMappings("com.kenticocloud");

    //modify default baseurl to point to test server, this is private so using reflection
    String testServerUri = httpHost.toURI() + "/%s";
    Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions");
    deliveryOptionsField.setAccessible(true);
    ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri);

    Object itemObj = client.getItem("on_roasts", Object.class);
    Assert.assertNotNull(itemObj);
    Assert.assertTrue(itemObj instanceof ArticleItem);
}
 
Example 19
Project: delivery-sdk-java   File: DeliveryClientTest.java   View source code 6 votes vote down vote up
@Test
public void testGetTypes() throws Exception {
    String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c";

    this.serverBootstrap.registerHandler(
            String.format("/%s/%s", projectId, "types"),
            (request, response, context) -> response.setEntity(
                    new InputStreamEntity(
                            this.getClass().getResourceAsStream("SampleContentTypeList.json")
                    )
            ));
    HttpHost httpHost = this.start();
    DeliveryClient client = new DeliveryClient(projectId);

    //modify default baseurl to point to test server, this is private so using reflection
    String testServerUri = httpHost.toURI() + "/%s";
    Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions");
    deliveryOptionsField.setAccessible(true);
    ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri);

    ContentTypesListingResponse types = client.getTypes();
    Assert.assertNotNull(types);
}
 
Example 20
Project: delivery-sdk-java   File: DeliveryClientTest.java   View source code 6 votes vote down vote up
@Test
public void testGetType() throws Exception {
    String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c";

    this.serverBootstrap.registerHandler(
            String.format("/%s/%s", projectId, "types/coffee"),
            (request, response, context) -> response.setEntity(
                    new InputStreamEntity(
                            this.getClass().getResourceAsStream("SampleContentType.json")
                    )
            ));
    HttpHost httpHost = this.start();
    DeliveryClient client = new DeliveryClient(projectId);

    //modify default baseurl to point to test server, this is private so using reflection
    String testServerUri = httpHost.toURI() + "/%s";
    Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions");
    deliveryOptionsField.setAccessible(true);
    ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri);

    ContentType type = client.getType("coffee");
    Assert.assertNotNull(type);
}
 
Example 21
Project: delivery-sdk-java   File: DeliveryClientTest.java   View source code 6 votes vote down vote up
@Test
public void testGetTypeElement() throws Exception {
    String projectId = "02a70003-e864-464e-b62c-e0ede97deb8c";

    this.serverBootstrap.registerHandler(
            String.format("/%s/%s", projectId, "types/coffee/elements/processing"),
            (request, response, context) -> response.setEntity(
                    new InputStreamEntity(
                            this.getClass().getResourceAsStream("SampleContentTypeElementResponse.json")
                    )
            ));
    HttpHost httpHost = this.start();
    DeliveryClient client = new DeliveryClient(projectId);

    //modify default baseurl to point to test server, this is private so using reflection
    String testServerUri = httpHost.toURI() + "/%s";
    Field deliveryOptionsField = client.getClass().getDeclaredField("deliveryOptions");
    deliveryOptionsField.setAccessible(true);
    ((DeliveryOptions) deliveryOptionsField.get(client)).setProductionEndpoint(testServerUri);

    Element element = client.getContentTypeElement("coffee", "processing");
    Assert.assertNotNull(element);
    Assert.assertEquals("processing", element.getCodeName());
    Assert.assertTrue(element instanceof MultipleChoiceElement);
}
 
Example 22
Project: mule-useful-experiments   File: Tests.java   View source code 6 votes vote down vote up
private static void doUpload(CloseableHttpClient client, String path) throws IOException {

        String url = String.format(
                "http://%s:%s/%s",
                TestProperties.getProperty("com.guido.host"),
                TestProperties.getProperty("com.guido.port"),
                path
        );

        InputStreamEntity requestEntity = new InputStreamEntity(
                new FileInputStream(BIG_XML_FILE_PATH), -1,
                ContentType.APPLICATION_OCTET_STREAM);

        // set chunked transfer encoding ie. no Content-length
        requestEntity.setChunked(true);

        HttpPost httpPost = new HttpPost((url));
        httpPost.setEntity(requestEntity);
        HttpResponse response = client.execute(httpPost);

        assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_OK));

    }
 
Example 23
Project: hadoop   File: AuthenticatorTestCase.java   View source code 6 votes vote down vote up
protected void _testAuthenticationHttpClient(Authenticator authenticator, boolean doPost) throws Exception {
  start();
  try {
    SystemDefaultHttpClient httpClient = getHttpClient();
    doHttpClientRequest(httpClient, new HttpGet(getBaseURL()));

    // Always do a GET before POST to trigger the SPNego negotiation
    if (doPost) {
      HttpPost post = new HttpPost(getBaseURL());
      byte [] postBytes = POST.getBytes();
      ByteArrayInputStream bis = new ByteArrayInputStream(postBytes);
      InputStreamEntity entity = new InputStreamEntity(bis, postBytes.length);

      // Important that the entity is not repeatable -- this means if
      // we have to renegotiate (e.g. b/c the cookie wasn't handled properly)
      // the test will fail.
      Assert.assertFalse(entity.isRepeatable());
      post.setEntity(entity);
      doHttpClientRequest(httpClient, post);
    }
  } finally {
    stop();
  }
}
 
Example 24
Project: aws-sdk-java-v2   File: RepeatableInputStreamRequestEntity.java   View source code 6 votes vote down vote up
/**
 * Creates a new RepeatableInputStreamRequestEntity using the information
 * from the specified request. If the input stream containing the request's
 * contents is repeatable, then this RequestEntity will report as being
 * repeatable.
 *
 * @param request The details of the request being written out (content type,
 *                content length, and content).
 */
public RepeatableInputStreamRequestEntity(final SdkHttpFullRequest request) {
    setChunked(false);

    /*
     * If we don't specify a content length when we instantiate our
     * InputStreamRequestEntity, then HttpClient will attempt to
     * buffer the entire stream contents into memory to determine
     * the content length.
     */
    long contentLength = request.firstMatchingHeader("Content-Length")
                                .map(this::parseContentLength)
                                .orElse(-1L);

    content = getContent(request);
    // TODO v2 MetricInputStreamEntity
    inputStreamRequestEntity = new InputStreamEntity(content, contentLength);
    setContent(content);
    setContentLength(contentLength);

    request.firstMatchingHeader("Content-Type").ifPresent(contentType -> {
        inputStreamRequestEntity.setContentType(contentType);
        setContentType(contentType);
    });
}
 
Example 25
Project: rawhttp   File: RawHttpComponentsClient.java   View source code 6 votes vote down vote up
public RawHttpResponse<CloseableHttpResponse> send(RawHttpRequest request) throws IOException {
    RequestBuilder builder = RequestBuilder.create(request.getMethod());
    builder.setUri(request.getUri());
    builder.setVersion(toProtocolVersion(request.getStartLine().getHttpVersion()));
    request.getHeaders().getHeaderNames().forEach((name) ->
            request.getHeaders().get(name).forEach(value ->
                    builder.addHeader(new BasicHeader(name, value))));

    request.getBody().ifPresent(b -> builder.setEntity(new InputStreamEntity(b.asStream())));

    CloseableHttpResponse response = httpClient.execute(builder.build());

    RawHttpHeaders headers = readHeaders(response);

    @Nullable LazyBodyReader body;
    if (response.getEntity() != null) {
        OptionalLong headerLength = RawHttp.parseContentLength(headers);
        @Nullable Long length = headerLength.isPresent() ? headerLength.getAsLong() : null;
        BodyType bodyType = RawHttp.getBodyType(headers, length);
        body = new LazyBodyReader(bodyType, response.getEntity().getContent(), length, false);
    } else {
        body = null;
    }

    return new RawHttpResponse<>(response, request, adaptStatus(response.getStatusLine()), headers, body);
}
 
Example 26
Project: PriorityOkHttp   File: OkApacheClient.java   View source code 6 votes vote down vote up
private static HttpResponse transformResponse(Response response) throws IOException {
  int code = response.code();
  String message = response.message();
  BasicHttpResponse httpResponse = new BasicHttpResponse(HTTP_1_1, code, message);

  ResponseBody body = response.body();
  InputStreamEntity entity = new InputStreamEntity(body.byteStream(), body.contentLength());
  httpResponse.setEntity(entity);

  Headers headers = response.headers();
  for (int i = 0, size = headers.size(); i < size; i++) {
    String name = headers.name(i);
    String value = headers.value(i);
    httpResponse.addHeader(name, value);
    if ("Content-Type".equalsIgnoreCase(name)) {
      entity.setContentType(value);
    } else if ("Content-Encoding".equalsIgnoreCase(name)) {
      entity.setContentEncoding(value);
    }
  }

  return httpResponse;
}
 
Example 27
Project: aliyun-oss-hadoop-fs   File: AuthenticatorTestCase.java   View source code 6 votes vote down vote up
protected void _testAuthenticationHttpClient(Authenticator authenticator, boolean doPost) throws Exception {
  start();
  try {
    SystemDefaultHttpClient httpClient = getHttpClient();
    doHttpClientRequest(httpClient, new HttpGet(getBaseURL()));

    // Always do a GET before POST to trigger the SPNego negotiation
    if (doPost) {
      HttpPost post = new HttpPost(getBaseURL());
      byte [] postBytes = POST.getBytes();
      ByteArrayInputStream bis = new ByteArrayInputStream(postBytes);
      InputStreamEntity entity = new InputStreamEntity(bis, postBytes.length);

      // Important that the entity is not repeatable -- this means if
      // we have to renegotiate (e.g. b/c the cookie wasn't handled properly)
      // the test will fail.
      Assert.assertFalse(entity.isRepeatable());
      post.setEntity(entity);
      doHttpClientRequest(httpClient, post);
    }
  } finally {
    stop();
  }
}
 
Example 28
Project: stocator   File: SwiftAPIDirect.java   View source code 6 votes vote down vote up
/**
 * @param path path to object
 * @param inputStream input stream
 * @param account JOSS Account object
 * @param metadata custom metadata
 * @param size the object size
 * @param type the content type
 * @return HTTP response code
 * @throws IOException if error
 */
private static int httpPUT(String path,
    InputStream inputStream, JossAccount account, SwiftConnectionManager scm,
    Map<String, String> metadata, long size, String type)
        throws IOException {
  LOG.debug("HTTP PUT {} request on {}", path);
  HttpPut httpPut = new HttpPut(path);
  httpPut.addHeader("X-Auth-Token", account.getAuthToken());
  httpPut.addHeader("Content-Type", type);
  httpPut.addHeader(Constants.USER_AGENT_HTTP_HEADER, Constants.STOCATOR_USER_AGENT);
  if (metadata != null && !metadata.isEmpty()) {
    for (Map.Entry<String, String> entry : metadata.entrySet()) {
      httpPut.addHeader("X-Object-Meta-" + entry.getKey(), entry.getValue());
    }
  }
  RequestConfig config = RequestConfig.custom().setExpectContinueEnabled(true).build();
  httpPut.setConfig(config);
  InputStreamEntity entity = new InputStreamEntity(inputStream,size);
  httpPut.setEntity(entity);
  CloseableHttpClient httpclient = scm.createHttpConnection();
  CloseableHttpResponse response = httpclient.execute(httpPut);
  int responseCode = response.getStatusLine().getStatusCode();
  LOG.debug("HTTP PUT {} response. Status code {}", path, responseCode);
  response.close();
  return responseCode;
}
 
Example 29
Project: codePay   File: HttpClientUtil.java   View source code 6 votes vote down vote up
/**
 * 向指定URL发送POST方法的数据流请求
 *
 * @param url     发送请求的URL
 * @param message 请求数据
 * @param isProxy 是否使用代理
 * @return URL所代表远程资源的响应
 */
public static String sendPostStream(String url, String message, String encode, boolean isProxy) {
    SafeHttpClient httpClient = HttpClientFactory.getHttpClient(isProxy);
    HttpPost httpReq = new HttpPost(url);
    try {
        if (StringUtils.isNotBlank(message)) {
            // 构造最简单的字符串数据
            byte[] content = message.getBytes();
            InputStream inputStream = new ByteArrayInputStream(content);
            InputStreamEntity reqEntity = new InputStreamEntity(inputStream, content.length);
            reqEntity.setContentType("application/x-www-form-urlencoded");
            // 设置请求的数据
            httpReq.setEntity(reqEntity);
        }
        ResponseHandler<String> responseHandler = new SimpleResponseHandler(encode);
        return httpClient.execute(httpReq, responseHandler, new BasicHttpContext());
    } catch (Exception e) {
        LOGGER.error("sendPostStream请求远程地址失败,url:{},message:{},encode:{},isProxy:{},Exception:{}", url, message,
                encode, isProxy, ExceptionUtil.getException(e));
        httpReq.abort();
        httpClient.closeExpiredConnections();
    }
    return null;
}
 
Example 30
Project: whatsmars   File: HttpUtils.java   View source code 6 votes vote down vote up
/**
 * 发送body为输入流
 * sample
 */
public static String postBodyAsStream(String url,InputStream inputStream, String encoding) throws Exception{
    HttpPost httpPost = new HttpPost(url);
    HttpEntity body = new InputStreamEntity(inputStream);
    httpPost.setEntity(body);
    CloseableHttpResponse response = httpClient.execute(httpPost);
    try {
        HttpEntity entity = response.getEntity();
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            httpPost.abort();
            throw new RuntimeException("HttpClient,error status code :" + statusCode);
        }
        String result = null;
        if (entity != null) {
            result = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        return result;
    } finally {
        response.close();
    }
}
 
Example 31
Project: Okhttp   File: OkApacheClient.java   View source code 6 votes vote down vote up
private static HttpResponse transformResponse(Response response) {
  int code = response.code();
  String message = response.message();
  BasicHttpResponse httpResponse = new BasicHttpResponse(HTTP_1_1, code, message);

  ResponseBody body = response.body();
  InputStreamEntity entity = new InputStreamEntity(body.byteStream(), body.contentLength());
  httpResponse.setEntity(entity);

  Headers headers = response.headers();
  for (int i = 0, size = headers.size(); i < size; i++) {
    String name = headers.name(i);
    String value = headers.value(i);
    httpResponse.addHeader(name, value);
    if ("Content-Type".equalsIgnoreCase(name)) {
      entity.setContentType(value);
    } else if ("Content-Encoding".equalsIgnoreCase(name)) {
      entity.setContentEncoding(value);
    }
  }

  return httpResponse;
}
 
Example 32
Project: big-c   File: AuthenticatorTestCase.java   View source code 6 votes vote down vote up
protected void _testAuthenticationHttpClient(Authenticator authenticator, boolean doPost) throws Exception {
  start();
  try {
    SystemDefaultHttpClient httpClient = getHttpClient();
    doHttpClientRequest(httpClient, new HttpGet(getBaseURL()));

    // Always do a GET before POST to trigger the SPNego negotiation
    if (doPost) {
      HttpPost post = new HttpPost(getBaseURL());
      byte [] postBytes = POST.getBytes();
      ByteArrayInputStream bis = new ByteArrayInputStream(postBytes);
      InputStreamEntity entity = new InputStreamEntity(bis, postBytes.length);

      // Important that the entity is not repeatable -- this means if
      // we have to renegotiate (e.g. b/c the cookie wasn't handled properly)
      // the test will fail.
      Assert.assertFalse(entity.isRepeatable());
      post.setEntity(entity);
      doHttpClientRequest(httpClient, post);
    }
  } finally {
    stop();
  }
}
 
Example 33
Project: registry   File: AuthenticatorTestCase.java   View source code 6 votes vote down vote up
protected void _testAuthenticationHttpClient(Authenticator authenticator, boolean doPost) throws Exception {
    start();
    try {
        SystemDefaultHttpClient httpClient = getHttpClient();
        doHttpClientRequest(httpClient, new HttpGet(getBaseURL()));

        // Always do a GET before POST to trigger the SPNego negotiation
        if (doPost) {
            HttpPost post = new HttpPost(getBaseURL());
            byte[] postBytes = POST.getBytes();
            ByteArrayInputStream bis = new ByteArrayInputStream(postBytes);
            InputStreamEntity entity = new InputStreamEntity(bis, postBytes.length);

            // Important that the entity is not repeatable -- this means if
            // we have to renegotiate (e.g. b/c the cookie wasn't handled properly)
            // the test will fail.
            Assert.assertFalse(entity.isRepeatable());
            post.setEntity(entity);
            doHttpClientRequest(httpClient, post);
        }
    } finally {
        stop();
    }
}
 
Example 34
Project: fcrepo-api-x   File: JenaServiceRegistry.java   View source code 6 votes vote down vote up
@Override
public void register(final URI uri) {
    init.await();
    try {
        LOG.debug("Registering service {} ", uri);

        final HttpPatch patch = new HttpPatch(registryContainer);
        patch.setHeader(HttpHeaders.CONTENT_TYPE, SPARQL_UPDATE);
        patch.setEntity(new InputStreamEntity(patchAddService(uri)));

        try (CloseableHttpResponse resp = execute(patch)) {
            LOG.info("Adding service {} to registry {}", uri, registryContainer);
        }
    } catch (final Exception e) {
        throw new RuntimeException(String.format("Could not add <%s> to service registry <%s>", uri,
                registryContainer), e);
    }

    update(uri);
}
 
Example 35
Project: haven-platform   File: HttpProxy.java   View source code 6 votes vote down vote up
private HttpEntity createEntity(HttpServletRequest servletRequest) throws IOException {
    final String contentType = servletRequest.getContentType();
    // body with 'application/x-www-form-urlencoded' is handled by tomcat therefore we cannot
    // obtain it through input stream and need some workaround
    if (ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType)) {
        List<NameValuePair> entries = new ArrayList<>();
        // obviously that we also copy params from url, but we cannot differentiate its
        Enumeration<String> names = servletRequest.getParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            entries.add(new BasicNameValuePair(name, servletRequest.getParameter(name)));
        }
        return new UrlEncodedFormEntity(entries, servletRequest.getCharacterEncoding());
    }

    // Add the input entity (streamed)
    //  note: we don't bother ensuring we close the servletInputStream since the container handles it
    return new InputStreamEntity(servletRequest.getInputStream(),
            servletRequest.getContentLength(),
            ContentType.create(contentType));
}
 
Example 36
Project: vespa   File: ApacheGatewayConnection.java   View source code 6 votes vote down vote up
protected static InputStreamEntity zipAndCreateEntity(final InputStream inputStream) throws IOException {
    byte[] buffer = new byte[4096];
    GZIPOutputStream gzos = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        gzos = new GZIPOutputStream(baos);
        while (inputStream.available() > 0) {
            int length = inputStream.read(buffer);
            gzos.write(buffer, 0,length);
        }
    } finally {
        if (gzos != null)  {
            gzos.close();
        }
    }
    byte[] fooGzippedBytes = baos.toByteArray();
    return new InputStreamEntity(new ByteArrayInputStream(fooGzippedBytes), -1);
}
 
Example 37
Project: HackathonPADLS   File: TriggerActivity.java   View source code 6 votes vote down vote up
protected String doInBackground(String... urls) {
    String url = "";
    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"/audiorecordtest.3gp");
    try {
        HttpClient httpclient = new DefaultHttpClient();

        HttpPost httppost = new HttpPost(new URI(url));

        InputStreamEntity reqEntity = new InputStreamEntity(
                new FileInputStream(file), -1);
        reqEntity.setContentType("binary/octet-stream");
        reqEntity.setChunked(true); // Send in multiple parts if needed
        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);
        return response.toString();

    } catch (Exception e) {
        return e.getMessage().toString();
    }
}
 
Example 38
Project: downloadclient   File: XML.java   View source code 6 votes vote down vote up
/**
 * Getting a document by posting an xml to a url.
 * @param url the url
 * @param userName the username
 * @param password the password
 * @param postXML the xml to post
 * @param nameSpaceAware if namespace aware
 * @return the returned document
 * @throws URISyntaxException if the url is wrong
 * @throws IOException if something in io is wrong
 */
public static final Document getDocument(
        URL url,
        String userName,
        String password,
        String postXML,
        boolean nameSpaceAware)
        throws URISyntaxException, IOException {
    try (
        CloseableHttpClient client =
            HTTP.getClient(url, userName, password);
    ) {
        HttpPost request = HTTP.getPostRequest(url);
        DocumentResponseHandler handler =
                new DocumentResponseHandler(request);
        handler.setNamespaceAware(nameSpaceAware);
        InputStream inputStream =
                new ByteArrayInputStream(postXML.getBytes());
        InputStreamEntity inputStreamEntity = new InputStreamEntity(
                inputStream);
        request.setHeader("Content-type", "text/xml;charset=utf-8");
        request.setEntity(inputStreamEntity);
        return client.execute(request, handler);
    }
}
 
Example 39
Project: purecloud-iot   File: TestResponseProtocolCompliance.java   View source code 6 votes vote down vote up
@Test
public void consumesBodyIfOriginSendsOneInResponseToHEAD() throws Exception {
    final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(new HttpHead("http://foo.example.com/"));
    final int nbytes = 128;
    final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    setMinimalResponseHeaders(resp);
    resp.setHeader("Content-Length","" + nbytes);

    final Flag closed = new Flag();
    final ByteArrayInputStream bais = makeTrackableBody(nbytes, closed);
    resp.setEntity(new InputStreamEntity(bais, -1));

    impl.ensureProtocolCompliance(wrapper, resp);
    assertNull(resp.getEntity());
    assertTrue(closed.set || bais.read() == -1);
}
 
Example 40
Project: purecloud-iot   File: TestResponseProtocolCompliance.java   View source code 6 votes vote down vote up
@Test
public void consumesPartialContentFromOriginEvenIfNotRequested() throws Exception {
    final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(new HttpGet("http://foo.example.com/"));
    final int nbytes = 128;
    final HttpResponse resp = makePartialResponse(nbytes);

    final Flag closed = new Flag();
    final ByteArrayInputStream bais = makeTrackableBody(nbytes, closed);
    resp.setEntity(new InputStreamEntity(bais, -1));

    try {
        impl.ensureProtocolCompliance(wrapper, resp);
    } catch (final ClientProtocolException expected) {
    }
    assertTrue(closed.set || bais.read() == -1);
}