类org.apache.http.entity.InputStreamEntity源码实例Demo

下面列出了怎么用org.apache.http.entity.InputStreamEntity的API类实例代码及写法,或者点击链接到github查看源代码。

@Test
public void postNonRepeatableEntityTest() throws IOException {
  HttpPost httpPost = new HttpPost(
      "https://api.mch.weixin.qq.com/v3/marketing/favor/users/oHkLxt_htg84TUEbzvlMwQzVDBqo/coupons");


  InputStream stream = new ByteArrayInputStream(reqdata.getBytes("utf-8"));
  InputStreamEntity reqEntity = new InputStreamEntity(stream);
  reqEntity.setContentType("application/json");
  httpPost.setEntity(reqEntity);
  httpPost.addHeader("Accept", "application/json");

  CloseableHttpResponse response = httpClient.execute(httpPost);
  assertTrue(response.getStatusLine().getStatusCode() != 401);
  try {
    HttpEntity entity2 = response.getEntity();
    // do something useful with the response body
    // and ensure it is fully consumed
    EntityUtils.consume(entity2);
  } finally {
    response.close();
  }
}
 
源代码2 项目: hop   文件: HopServer.java
HttpPost buildSendExportMethod( String type, String load, InputStream is ) throws UnsupportedEncodingException {
  String serviceUrl = RegisterPackageServlet.CONTEXT_PATH;
  if ( type != null && load != null ) {
    serviceUrl +=
      "/?" + RegisterPackageServlet.PARAMETER_TYPE + "=" + type
        + "&" + RegisterPackageServlet.PARAMETER_LOAD + "=" + URLEncoder.encode( load, "UTF-8" );
  }

  String urlString = constructUrl( serviceUrl );
  if ( log.isDebug() ) {
    log.logDebug( BaseMessages.getString( PKG, "HopServer.DEBUG_ConnectingTo", urlString ) );
  }

  HttpPost method = new HttpPost( urlString );
  method.setEntity( new InputStreamEntity( is ) );
  method.addHeader( new BasicHeader( "Content-Type", "binary/zip" ) );

  return method;
}
 
源代码3 项目: cups4j   文件: IppCreateJobOperation.java
private static IppResult sendRequest(URI uri, ByteBuffer ippBuf) throws IOException {
    CloseableHttpClient client = HttpClients.custom().build();

    HttpPost httpPost = new HttpPost(uri);
    httpPost.setConfig(getRequestConfig());

    byte[] bytes = new byte[ippBuf.limit()];
    ippBuf.get(bytes);

    ByteArrayInputStream headerStream = new ByteArrayInputStream(bytes);

    // set length to -1 to advice the entity to read until EOF
    InputStreamEntity requestEntity = new InputStreamEntity(headerStream, -1);

    requestEntity.setContentType(IPP_MIME_TYPE);
    httpPost.setEntity(requestEntity);
    CloseableHttpResponse httpResponse = client.execute(httpPost);
    return toIppResult(httpResponse);
}
 
源代码4 项目: cups4j   文件: IppSendDocumentOperation.java
private IppResult sendRequest(URI uri, ByteBuffer ippBuf, InputStream documentStream) throws IOException {
    HttpPost httpPost = new HttpPost(uri);
    httpPost.setConfig(getRequestConfig());
    
    byte[] bytes = new byte[ippBuf.limit()];
    ippBuf.get(bytes);
    ByteArrayInputStream headerStream = new ByteArrayInputStream(bytes);

    InputStream inputStream = new SequenceInputStream(headerStream, documentStream);
    InputStreamEntity requestEntity = new InputStreamEntity(inputStream, -1);
    requestEntity.setContentType(IPP_MIME_TYPE);
    httpPost.setEntity(requestEntity);

    CloseableHttpClient client = HttpClients.custom().build();
    try {
        CloseableHttpResponse httpResponse = client.execute(httpPost);
        LOG.info("Received from {}: {}", uri, httpResponse);
        return getIppResult(httpResponse);
    } finally {
        client.close();
    }
}
 
源代码5 项目: devops-cm-client   文件: CMODataAbapClient.java
public String upload(String transportId, InputStream content) throws IOException, CMODataClientException, UnexpectedHttpResponseException {

        checkArgument(! isNullOrEmpty(transportId), "TransportId is null or empty.");
        checkArgument(content != null, "No content provided for upload.");

        //
        // Below we work with a non-repeatable entity. This is fine since we can be sure the
        // request does not need to be repeated. Reason: the need for repeating a request inside
        // the client (transparent for the caller) is an authentification scenario (first request
        // without credentials, resulting in 401, repeated request with credentials). When uploading
        // the content we are already authenticated since we have to fetch the csrf token beforehand
        // in any case.
        //

        try (CloseableHttpClient client = clientFactory.createClient()) {
            HttpPost request = requestBuilder.upload(transportId);
            request.setEntity(new InputStreamEntity(content));
            request.addHeader("x-csrf-token", getCSRFToken());
            try (CloseableHttpResponse response = client.execute(request)) {
                hasStatusOrFail(response, HttpStatus.SC_CREATED);
                return response.getHeaders("location")[0].getValue();
            }
        }
    }
 
源代码6 项目: hadoop   文件: AuthenticatorTestCase.java
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();
  }
}
 
/**
 * 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 HttpExecuteRequest 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.httpRequest().firstMatchingHeader("Content-Length")
                                .map(this::parseContentLength)
                                .orElse(-1L);

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

    request.httpRequest().firstMatchingHeader("Content-Type").ifPresent(contentType -> {
        inputStreamRequestEntity.setContentType(contentType);
        setContentType(contentType);
    });
}
 
源代码8 项目: rawhttp   文件: RawHttpComponentsClient.java
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.asRawStream())));

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

    RawHttpHeaders headers = readHeaders(response);
    StatusLine statusLine = adaptStatus(response.getStatusLine());

    @Nullable LazyBodyReader body;
    if (response.getEntity() != null) {
        FramedBody framedBody = http.getFramedBody(statusLine, headers);
        body = new LazyBodyReader(framedBody, response.getEntity().getContent());
    } else {
        body = null;
    }

    return new RawHttpResponse<>(response, request, statusLine, headers, body);
}
 
源代码9 项目: big-c   文件: AuthenticatorTestCase.java
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();
  }
}
 
源代码10 项目: lucene-solr   文件: HttpSolrClient.java
private void fillSingleContentStream(Collection<ContentStream> streams, HttpEntityEnclosingRequestBase postOrPut) throws IOException {
  // Single stream as body
  // Using a loop just to get the first one
  final ContentStream[] contentStream = new ContentStream[1];
  for (ContentStream content : streams) {
    contentStream[0] = content;
    break;
  }
  Long size = contentStream[0].getSize();
  postOrPut.setEntity(new InputStreamEntity(contentStream[0].getStream(), size == null ? -1 : size) {
    @Override
    public Header getContentType() {
      return new BasicHeader("Content-Type", contentStream[0].getContentType());
    }

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

}
 
源代码11 项目: lucene-solr   文件: SolrSchemalessExampleTest.java
@Test
public void testArbitraryJsonIndexing() throws Exception  {
  HttpSolrClient client = (HttpSolrClient) getSolrClient();
  client.deleteByQuery("*:*");
  client.commit();
  assertNumFound("*:*", 0); // make sure it got in

  // two docs, one with uniqueKey, another without it
  String json = "{\"id\":\"abc1\", \"name\": \"name1\"} {\"name\" : \"name2\"}";
  HttpClient httpClient = client.getHttpClient();
  HttpPost post = new HttpPost(client.getBaseURL() + "/update/json/docs");
  post.setHeader("Content-Type", "application/json");
  post.setEntity(new InputStreamEntity(
      new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)), -1));
  HttpResponse response = httpClient.execute(post, HttpClientUtil.createNewHttpClientRequestContext());
  Utils.consumeFully(response.getEntity());
  assertEquals(200, response.getStatusLine().getStatusCode());
  client.commit();
  assertNumFound("*:*", 2);
}
 
源代码12 项目: registry   文件: AuthenticatorTestCase.java
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();
    }
}
 
源代码13 项目: haven-platform   文件: HttpProxy.java
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));
}
 
源代码14 项目: vespa   文件: ApacheGatewayConnection.java
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);
}
 
源代码15 项目: stocator   文件: SwiftAPIDirect.java
/**
 * @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);
  final 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());
    }
  }
  final RequestConfig config = RequestConfig.custom().setExpectContinueEnabled(true).build();
  httpPut.setConfig(config);
  final InputStreamEntity entity = new InputStreamEntity(inputStream, size);
  httpPut.setEntity(entity);
  final CloseableHttpClient httpclient = scm.createHttpConnection();
  final CloseableHttpResponse response = httpclient.execute(httpPut);
  int responseCode = response.getStatusLine().getStatusCode();
  LOG.debug("HTTP PUT {} response. Status code {}", path, responseCode);
  response.close();
  return responseCode;
}
 
public DCContentUploader upload() throws IOException
{
    HttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    post.setHeader("Content-Type", "application/octet-stream");
    post.setEntity(new InputStreamEntity(content));

    HttpResponse httpResponse = client.execute(post);
    status = httpResponse.getStatusLine().getStatusCode();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    StreamUtils.copy(httpResponse.getEntity().getContent(), os);
    response = os.toString("UTF-8");
    headers = new HttpHeaders();
    for(Header header : httpResponse.getAllHeaders()) {
        headers.add(header.getName(), header.getValue());
    }
    post.releaseConnection();
    return this;
}
 
源代码17 项目: nexus-public   文件: OrientPyPiProxyFacetImpl.java
@Override
protected HttpRequestBase buildFetchHttpRequest(final URI uri, final Context context) {
  Request request = context.getRequest();
  // If we're doing a search operation, we have to proxy the content of the XML-RPC POST request to the PyPI server...
  if (isSearchRequest(request)) {
    Payload payload = checkNotNull(request.getPayload());
    try {
      ContentType contentType = ContentType.parse(payload.getContentType());
      HttpPost post = new HttpPost(uri);
      post.setEntity(new InputStreamEntity(payload.openInputStream(), payload.getSize(), contentType));
      return post;
    }
    catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  return super.buildFetchHttpRequest(uri, context); // URI needs to be replaced here
}
 
源代码18 项目: elasticsearch   文件: SearchProxyControllerTest.java
@Test
public void willForwardSearchRequestToAChosenNode() throws Exception {
    final String chosenNode = "1.0.0.1:1002";

    when(elasticsearchScheduler.getTasks()).thenReturn(createTasksMap(3));
    when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class))).thenReturn(httpResponse);
    when(httpResponse.getEntity()).thenReturn(new InputStreamEntity(new ByteArrayInputStream("Search result".getBytes("UTF-8"))));

    final ResponseEntity<InputStreamResource> search = controller.search("test", chosenNode);
    assertEquals(200, search.getStatusCode().value());

    assertEquals(chosenNode, search.getHeaders().getFirst("X-ElasticSearch-host"));
    final ArgumentCaptor<HttpHost> httpHostArgumentCaptor = ArgumentCaptor.forClass(HttpHost.class);
    final ArgumentCaptor<HttpRequest> httpRequestArgumentCaptor = ArgumentCaptor.forClass(HttpRequest.class);
    verify(httpClient).execute(httpHostArgumentCaptor.capture(), httpRequestArgumentCaptor.capture());
    assertEquals(HOSTNAME, httpHostArgumentCaptor.getValue().getHostName());
    assertEquals("/_search?q=test", httpRequestArgumentCaptor.getValue().getRequestLine().getUri());
}
 
源代码19 项目: components   文件: BulkV2Connection.java
public void uploadDataFromStream(String jobId, InputStream input) throws BulkV2ClientException {
    try {
        String endpoint = getRestEndpoint();
        endpoint = endpoint + "jobs/ingest/" + jobId + "/batches";
        HttpPut httpPut = (HttpPut) createRequest(endpoint, HttpMethod.PUT);

        InputStreamEntity entity = new InputStreamEntity(input, -1);
        entity.setContentType(CSV_CONTENT_TYPE);
        entity.setChunked(config.useChunkedPost());

        httpPut.setEntity(entity);
        HttpResponse response = httpclient.execute(httpPut);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
            throw new BulkV2ClientException(response.getStatusLine().getReasonPhrase());
        }
    } catch (BulkV2ClientException bec) {
        throw bec;
    } catch (IOException e) {
        throw new BulkV2ClientException(MESSAGES.getMessage("error.job.upload"), e);
    }
}
 
源代码20 项目: data-prep   文件: CreateOrUpdateDataSet.java
/**
 * Private constructor.
 *
 * @param id the dataset id.
 * @param name the dataset name.
 * @param dataSetContent the new dataset content.
 */
private CreateOrUpdateDataSet(String id, String name, long size, InputStream dataSetContent) {
    super(GenericCommand.DATASET_GROUP);
    execute(() -> {
        try {
            URIBuilder uriBuilder = new URIBuilder(datasetServiceUrl + "/datasets/" + id + "/raw/");
            if (!StringUtils.isEmpty(name)) {
                uriBuilder.addParameter("name", name);
            }
            uriBuilder.addParameter("size", String.valueOf(size));
            final HttpPut put = new HttpPut(uriBuilder.build()); // $NON-NLS-1$ //$NON-NLS-2$
            put.setEntity(new InputStreamEntity(dataSetContent));
            return put;
        } catch (URISyntaxException e) {
            throw new TDPException(UNEXPECTED_EXCEPTION, e);
        }
    });
    onError(e -> {
        if (e instanceof TDPException) {
            return passthrough().apply(e);
        }
        return new TDPException(UNABLE_TO_CREATE_OR_UPDATE_DATASET, e);
    });
    on(HttpStatus.NO_CONTENT, HttpStatus.ACCEPTED).then(emptyString());
    on(HttpStatus.OK).then(asString());
}
 
源代码21 项目: data-prep   文件: PreparationUpdateAction.java
private HttpRequestBase onExecute(String preparationId, String stepId, AppendStep updatedStep) {
    try {
        final String url = preparationServiceUrl + "/preparations/" + preparationId + "/actions/" + stepId;

        final Optional<StepDiff> firstStepDiff = toStream(StepDiff.class, objectMapper, input).findFirst();
        if (firstStepDiff.isPresent()) { // Only interested in first one
            final StepDiff diff = firstStepDiff.get();
            updatedStep.setDiff(diff);
        }
        final String stepAsString = objectMapper.writeValueAsString(updatedStep);

        final HttpPut actionAppend = new HttpPut(url);
        final InputStream stepInputStream = new ByteArrayInputStream(stepAsString.getBytes());

        actionAppend.setHeader(new BasicHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE));
        actionAppend.setEntity(new InputStreamEntity(stepInputStream));
        return actionAppend;
    } catch (IOException e) {
        throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
    }
}
 
源代码22 项目: cxf   文件: CXF4130Test.java
@Test
public void testCxf4130() throws Exception {
    InputStream body = getClass().getResourceAsStream("cxf4130data.txt");
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(ADDRESS);
    post.setEntity(new InputStreamEntity(body, ContentType.TEXT_XML));
    CloseableHttpResponse response = client.execute(post);

    Document doc = StaxUtils.read(response.getEntity().getContent());
    Element root = doc.getDocumentElement();
    Node child = root.getFirstChild();

    boolean foundBody = false;
    while (child != null) {
        if ("Body".equals(child.getLocalName())) {
            foundBody = true;
            assertEquals(1, child.getChildNodes().getLength());
            assertEquals("FooResponse", child.getFirstChild().getLocalName());
        }
        child = child.getNextSibling();
    }
    assertTrue("Did not find the soap:Body element", foundBody);
}
 
源代码23 项目: cxf   文件: JAXRSMultipartTest.java
private void doAddBook(String type, String address, InputStream is, int status) throws Exception {

        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(address);

        String ct = type + "; type=\"text/xml\"; " + "start=\"rootPart\"; "
            + "boundary=\"----=_Part_4_701508.1145579811786\"";
        post.setHeader("Content-Type", ct);

        post.setEntity(new InputStreamEntity(is));

        try {
            CloseableHttpResponse response = client.execute(post);
            assertEquals(status, response.getStatusLine().getStatusCode());
            if (status == 200) {
                InputStream expected = getClass().getResourceAsStream("resources/expected_add_book.txt");
                assertEquals(stripXmlInstructionIfNeeded(getStringFromInputStream(expected)),
                             stripXmlInstructionIfNeeded(EntityUtils.toString(response.getEntity())));
            }
        } finally {
            // Release current connection to the connection pool once you are done
            post.releaseConnection();
        }
    }
 
源代码24 项目: cxf   文件: JAXRSMultipartTest.java
private void doAddFormBook(String address, String resourceName, int status) throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(address);

    String ct = "multipart/form-data; boundary=bqJky99mlBWa-ZuqjC53mG6EzbmlxB";
    post.setHeader("Content-Type", ct);
    InputStream is =
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/" + resourceName);
    post.setEntity(new InputStreamEntity(is));

    try {
        CloseableHttpResponse response = client.execute(post);
        assertEquals(status, response.getStatusLine().getStatusCode());
        if (status == 200) {
            InputStream expected = getClass().getResourceAsStream("resources/expected_add_book.txt");
            assertEquals(stripXmlInstructionIfNeeded(getStringFromInputStream(expected)),
                         stripXmlInstructionIfNeeded(EntityUtils.toString(response.getEntity())));
        }
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}
 
源代码25 项目: VolleyBall   文件: AssetGenerator.java
public HttpResponse generateResponse(Context aContext, Route aRoute, Map<String, String> aReplace) {
    try {
        String test = mText;
        for (String aKey : aReplace.keySet()) {
            android.util.Log.d("AssetGenerator", "Replacing: "+ aKey);
            String regex = "\\{" + aKey.substring(1, aKey.length() - 1) + "\\}";
            test= test.replaceAll(regex, aReplace.get(aKey));
        }

        InputStream is = aContext.getAssets().open(test);
        HttpResponse response = FACTORY.newHttpResponse(HTTP_1_1, 200, CONTEXT);
        response.setEntity(new InputStreamEntity(is, is.available()));
        return response;
    } catch (Exception e) {
        e.printStackTrace();
        return SERVER_ERROR;
    }
}
 
源代码26 项目: bintray-client-java   文件: BintrayImpl.java
private List<RequestRunner> createPutRequestRunners(Map<String, InputStream> uriAndStreamMap, Map<String, String> headers, List<BintrayCallException> errors) {
    List<RequestRunner> runners = new ArrayList<>();
    List<HttpPut> requests = new ArrayList<>();
    log.debug("Creating PUT requests and RequestRunners for execution");
    for (String apiPath : uriAndStreamMap.keySet()) {
        HttpPut putRequest;
        try {
            putRequest = new HttpPut(createUrl(apiPath));
        } catch (BintrayCallException bce) {
            errors.add(bce);
            continue;
        }
        HttpEntity requestEntity = new InputStreamEntity(uriAndStreamMap.get(apiPath));
        putRequest.setEntity(requestEntity);
        setHeaders(putRequest, headers);
        requests.add(putRequest);
    }

    for (HttpPut request : requests) {
        RequestRunner runner = new RequestRunner(request, client, responseHandler);
        runners.add(runner);
    }
    return runners;
}
 
源代码27 项目: karate   文件: ApacheHttpUtils.java
public static HttpEntity getEntity(InputStream is, String mediaType, Charset charset) {
    try {
        return new InputStreamEntity(is, is.available(), getContentType(mediaType, charset));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }         
}
 
源代码28 项目: sanshanblog   文件: AbstractWebUtils.java
/**
 * POST请求
 *
 * @param url               URL
 * @param inputStreamEntity 请求体
 * @param encording 编码格式
 * @return 返回结果
 */
public static String post(String url, InputStreamEntity inputStreamEntity, String encording) {

    String result = null;
    try {
        HttpPost httpPost = new HttpPost(url);
        inputStreamEntity.setContentEncoding(encording);
        httpPost.setEntity(inputStreamEntity);
        CloseableHttpResponse httpResponse = HTTP_CLIENT.execute(httpPost);
        result = consumeResponse(httpResponse, encording);
    } catch (ParseException | IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    return result;
}
 
源代码29 项目: sanshanblog   文件: AbstractWebUtils.java
/**
 * 利用证书请求微信
 *
 * @param certPath 证书路径
 * @param passwd   证书密码
 * @param uri      请求地址
 * @param entity   请求体xml内容
 * @param encording 编码格式
 * @throws Exception 异常
 * @return 得到的结果
 */
public static String post(String certPath, String passwd, String uri, InputStreamEntity entity,
                          String encording) throws Exception {
    String result = null;
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File(certPath));
    try {
        keyStore.load(instream, passwd.toCharArray());
    } finally {
        instream.close();
    }
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, passwd.toCharArray()).build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"},
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {
        HttpPost httpPost = new HttpPost(uri);
        entity.setContentEncoding(encording);
        httpPost.setEntity(entity);
        CloseableHttpResponse httpResponse = httpclient.execute(httpPost);
        result = consumeResponse(httpResponse, encording);
    } finally {
        httpclient.close();
    }
    return result;
}
 
/**
 * 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 Request<?> 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.
     *
     * TODO: It'd be nice to have easier access to content length and
     *       content type from the request, instead of having to look
     *       directly into the headers.
     */
    long contentLength = -1;
    try {
        String contentLengthString = request.getHeaders().get("Content-Length");
        if (contentLengthString != null) {
            contentLength = Long.parseLong(contentLengthString);
        }
    } catch (NumberFormatException nfe) {
        log.warn("Unable to parse content length from request.  " +
                "Buffering contents in memory.");
    }

    String contentType = request.getHeaders().get("Content-Type");
    ThroughputMetricType type = ServiceMetricTypeGuesser
            .guessThroughputMetricType(request,
                    ServiceMetricType.UPLOAD_THROUGHPUT_NAME_SUFFIX,
                    ServiceMetricType.UPLOAD_BYTE_COUNT_NAME_SUFFIX);

    content = getContent(request);
    inputStreamRequestEntity = (type == null) ? new InputStreamEntity(content, contentLength) :
            new MetricInputStreamEntity(type, content, contentLength);
    inputStreamRequestEntity.setContentType(contentType);

    setContent(content);
    setContentType(contentType);
    setContentLength(contentLength);
}
 
 类所在包
 类方法
 同包方法