Java 类org.apache.http.HttpEntityEnclosingRequest 实例源码

项目:http-fetcher    文件:SimpleHttpFetcher.java   
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Decide about retry #" + executionCount + " for exception " + exception.getMessage());
    }

    if (executionCount >= _maxRetryCount) {
        // Do not retry if over max retry count
        return false;
    } else if (exception instanceof NoHttpResponseException) {
        // Retry if the server dropped connection on us
        return true;
    } else if (exception instanceof SSLHandshakeException) {
        // Do not retry on SSL handshake exception
        return false;
    }

    HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
    boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
    // Retry if the request is considered idempotent
    return idempotent;
}
项目:dtsopensource    文件:HttpProtocolParent.java   
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    if (executionCount >= 5) {// 如果已经重试了5次,就放弃
        return false;
    }
    if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
        return true;
    }
    if (exception instanceof InterruptedIOException) {// 超时
        return false;
    }
    if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
        return false;
    }
    if (exception instanceof UnknownHostException) {// 目标服务器不可达
        return false;
    }
    if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
        return false;
    }
    if (exception instanceof SSLException) {// SSL握手异常
        return false;
    }
    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();
    // 如果请求是幂等的,就再次尝试
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return true;
    }
    return false;
}
项目:elasticsearch_my    文件:RestClientSingleHostTests.java   
/**
 * Verifies the content of the {@link HttpRequest} that's internally created and passed through to the http client
 */
@SuppressWarnings("unchecked")
public void testInternalHttpRequest() throws Exception {
    ArgumentCaptor<HttpAsyncRequestProducer> requestArgumentCaptor = ArgumentCaptor.forClass(HttpAsyncRequestProducer.class);
    int times = 0;
    for (String httpMethod : getHttpMethods()) {
        HttpUriRequest expectedRequest = performRandomRequest(httpMethod);
        verify(httpClient, times(++times)).<HttpResponse>execute(requestArgumentCaptor.capture(),
                any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class));
        HttpUriRequest actualRequest = (HttpUriRequest)requestArgumentCaptor.getValue().generateRequest();
        assertEquals(expectedRequest.getURI(), actualRequest.getURI());
        assertEquals(expectedRequest.getClass(), actualRequest.getClass());
        assertArrayEquals(expectedRequest.getAllHeaders(), actualRequest.getAllHeaders());
        if (expectedRequest instanceof HttpEntityEnclosingRequest) {
            HttpEntity expectedEntity = ((HttpEntityEnclosingRequest) expectedRequest).getEntity();
            if (expectedEntity != null) {
                HttpEntity actualEntity = ((HttpEntityEnclosingRequest) actualRequest).getEntity();
                assertEquals(EntityUtils.toString(expectedEntity), EntityUtils.toString(actualEntity));
            }
        }
    }
}
项目:aws-request-signing-apache-interceptor    文件:AWSRequestSigningApacheInterceptorTest.java   
@Test
public void testSimpleSigner() throws Exception {
    HttpEntityEnclosingRequest request =
            new BasicHttpEntityEnclosingRequest("GET", "/query?a=b");
    request.setEntity(new StringEntity("I'm an entity"));
    request.addHeader("foo", "bar");
    request.addHeader("content-length", "0");

    HttpCoreContext context = new HttpCoreContext();
    context.setTargetHost(HttpHost.create("localhost"));

    createInterceptor().process(request, context);

    assertEquals("bar", request.getFirstHeader("foo").getValue());
    assertEquals("wuzzle", request.getFirstHeader("Signature").getValue());
    assertNull(request.getFirstHeader("content-length"));
}
项目:aws-request-signing-apache-interceptor    文件:AWSRequestSigningApacheInterceptorTest.java   
@Test
public void testEncodedUriSigner() throws Exception {
    HttpEntityEnclosingRequest request =
            new BasicHttpEntityEnclosingRequest("GET", "/foo-2017-02-25%2Cfoo-2017-02-26/_search?a=b");
    request.setEntity(new StringEntity("I'm an entity"));
    request.addHeader("foo", "bar");
    request.addHeader("content-length", "0");

    HttpCoreContext context = new HttpCoreContext();
    context.setTargetHost(HttpHost.create("localhost"));

    createInterceptor().process(request, context);

    assertEquals("bar", request.getFirstHeader("foo").getValue());
    assertEquals("wuzzle", request.getFirstHeader("Signature").getValue());
    assertNull(request.getFirstHeader("content-length"));
    assertEquals("/foo-2017-02-25%2Cfoo-2017-02-26/_search", request.getFirstHeader("resourcePath").getValue());
}
项目:allure-java    文件:AllureHttpClientRequest.java   
@Override
public void process(final HttpRequest request,
                    final HttpContext context) throws HttpException, IOException {
    final HttpRequestAttachment.Builder builder = create("Request", request.getRequestLine().getUri())
            .withMethod(request.getRequestLine().getMethod());

    Stream.of(request.getAllHeaders())
            .forEach(header -> builder.withHeader(header.getName(), header.getValue()));

    if (request instanceof HttpEntityEnclosingRequest) {
        final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();

        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        entity.writeTo(os);

        final String body = new String(os.toByteArray(), StandardCharsets.UTF_8);
        builder.withBody(body);
    }

    final HttpRequestAttachment requestAttachment = builder.build();
    processor.addAttachment(requestAttachment, renderer);
}
项目:springboot-security-wechat    文件:HttpClientFactory.java   
@Override
  public boolean retryRequest(
          IOException exception,
          int executionCount,
          HttpContext context) {
if (executionCount > retryExecutionCount) {
          return false;
      }
      if (exception instanceof InterruptedIOException) {
          return false;
      }
      if (exception instanceof UnknownHostException) {
          return false;
      }
      if (exception instanceof ConnectTimeoutException) {
          return true;
      }
      if (exception instanceof SSLException) {
          return false;
      }
      HttpClientContext clientContext = HttpClientContext.adapt(context);
      HttpRequest request = clientContext.getRequest();
      boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
      if (idempotent) {
          // Retry if the request is considered idempotent
          return true;
      }
      return false;
  }
项目:lams    文件:HttpComponentsAsyncClientHttpRequest.java   
@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(HttpHeaders headers, byte[] bufferedOutput)
        throws IOException {

    HttpComponentsClientHttpRequest.addHeaders(this.httpRequest, headers);

    if (this.httpRequest instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) this.httpRequest;
        HttpEntity requestEntity = new NByteArrayEntity(bufferedOutput);
        entityEnclosingRequest.setEntity(requestEntity);
    }

    final HttpResponseFutureCallback callback = new HttpResponseFutureCallback();
    final Future<HttpResponse> futureResponse =
            this.httpClient.execute(this.httpRequest, this.httpContext, callback);
    return new ClientHttpResponseFuture(futureResponse, callback);
}
项目:lams    文件:RequestExpectContinue.java   
public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
        // Do not send the expect header if request body is known to be empty
        if (entity != null && entity.getContentLength() != 0) {
            ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
            if (HttpProtocolParams.useExpectContinue(request.getParams())
                    && !ver.lessEquals(HttpVersion.HTTP_1_0)) {
                request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE);
            }
        }
    }
}
项目:NetDiscovery    文件:RetryHandler.java   
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {

    if (executionCount >= 3) {// 如果已经重试了3次,就放弃
        return false;
    }

    if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
        return true;
    }

    if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
        return false;
    }

    if (exception instanceof InterruptedIOException) {// 超时
        return true;
    }

    if (exception instanceof UnknownHostException) {// 目标服务器不可达
        return false;
    }

    if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
        return false;
    }

    if (exception instanceof SSLException) {// ssl握手异常
        return false;
    }

    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();

    // 如果请求是幂等的,就再次尝试
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return true;
    }
    return false;
}
项目:PicCrawler    文件:RetryHandler.java   
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {

    if (executionCount >= 3) {// 如果已经重试了3次,就放弃
        return false;
    }

    if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
        return true;
    }

    if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
        return false;
    }

    if (exception instanceof InterruptedIOException) {// 超时
        return true;
    }

    if (exception instanceof UnknownHostException) {// 目标服务器不可达
        return false;
    }

    if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
        return false;
    }

    if (exception instanceof SSLException) {// ssl握手异常
        return false;
    }

    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();

    // 如果请求是幂等的,就再次尝试
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return true;
    }
    return false;
}
项目:ProxyPool    文件:RetryHandler.java   
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {

    if (executionCount >= 3) {// 如果已经重试了3次,就放弃
        return false;
    }

    if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
        return true;
    }

    if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
        return false;
    }

    if (exception instanceof InterruptedIOException) {// 超时
        return true;
    }

    if (exception instanceof UnknownHostException) {// 目标服务器不可达
        return false;
    }

    if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
        return false;
    }

    if (exception instanceof SSLException) {// ssl握手异常
        return false;
    }

    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();

    // 如果请求是幂等的,就再次尝试
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return true;
    }
    return false;
}
项目:camelgateway    文件:CamelGatewaySbb.java   
private void pushContent(HttpUriRequest request, String contentType, String contentEncoding, byte[] content) {

        // TODO: check other preconditions?
        if (contentType != null && content != null && request instanceof HttpEntityEnclosingRequest) {
            BasicHttpEntity entity = new BasicHttpEntity();
            entity.setContent(new ByteArrayInputStream(content));
            entity.setContentLength(content.length);
            entity.setChunked(false);
            if (contentEncoding != null)
                entity.setContentEncoding(contentEncoding);
            entity.setContentType(contentType);
            HttpEntityEnclosingRequest rr = (HttpEntityEnclosingRequest) request;
            rr.setEntity(entity);
        }

    }
项目:spring4-understanding    文件:HttpComponentsAsyncClientHttpRequest.java   
@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(HttpHeaders headers, byte[] bufferedOutput)
        throws IOException {

    HttpComponentsClientHttpRequest.addHeaders(this.httpRequest, headers);

    if (this.httpRequest instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) this.httpRequest;
        HttpEntity requestEntity = new NByteArrayEntity(bufferedOutput);
        entityEnclosingRequest.setEntity(requestEntity);
    }

    final HttpResponseFutureCallback callback = new HttpResponseFutureCallback();
    final Future<HttpResponse> futureResponse =
            this.httpClient.execute(this.httpRequest, this.httpContext, callback);
    return new ClientHttpResponseFuture(futureResponse, callback);
}
项目:LAS    文件:LASProxy.java   
public boolean retryRequest(
        IOException exception,
        int executionCount,
        HttpContext context) {
    if (executionCount >= 5) {
        // Do not retry if over max retry count
        return false;
    }
    if (exception instanceof InterruptedIOException) {
        // Timeout
        return false;
    }
    if (exception instanceof UnknownHostException) {
        // Unknown host
        return false;
    }
    if (exception instanceof ConnectTimeoutException) {
        // Connection refused
        return false;
    }
    if (exception instanceof SSLException) {
        // SSL handshake exception
        return false;
    }
    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();
    boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
    if (idempotent) {
        // Retry if the request is considered idempotent
        return true;
    }
    return false;
}
项目:dms-webapp    文件:HttpConnectionManager.java   
/**
 * 自定义的恢复策略
 */
public boolean retryRequest(IOException exception, int exceptionCount,
        HttpContext context) {
    if (exceptionCount >= 3)
        return false;
    if (exception instanceof InterruptedIOException) {
        return false;
    }
    if (exception instanceof UnknownHostException) {
        return false;
    }
    if (exception instanceof ConnectTimeoutException) {
        return false;
    }
    if (exception instanceof SSLException) {
        return false;
    }
    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();
    boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
    if (idempotent) {
        return true;
    }
    return false;
}
项目:remote-files-sync    文件:RequestExpectContinue.java   
public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {
    Args.notNull(request, "HTTP request");

    if (!request.containsHeader(HTTP.EXPECT_DIRECTIVE)) {
        if (request instanceof HttpEntityEnclosingRequest) {
            final ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
            final HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
            // Do not send the expect header if request body is known to be empty
            if (entity != null
                    && entity.getContentLength() != 0 && !ver.lessEquals(HttpVersion.HTTP_1_0)) {
                final HttpClientContext clientContext = HttpClientContext.adapt(context);
                final RequestConfig config = clientContext.getRequestConfig();
                if (config.isExpectContinueEnabled()) {
                    request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE);
                }
            }
        }
    }
}
项目:sinacloud-sdk-java    文件:HttpMethodReleaseInputStream.java   
/**
 * Constructs an input stream based on an {@link HttpMethod} object
 * representing an HTTP connection. If a connection input stream is
 * available, this constructor wraps the underlying input stream and makes
 * that stream available. If no underlying connection is available, an empty
 * {@link ByteArrayInputStream} is made available.
 * 
 * @param httpMethod
 *            The HTTP method being executed, whose response content is to
 *            be wrapped.
 */
public HttpMethodReleaseInputStream(HttpEntityEnclosingRequest httpMethod) {
    this.httpRequest = httpMethod;

    try {
        this.inputStream = httpMethod.getEntity().getContent();
    } catch (IOException e) {
        if (log.isWarnEnabled()) {
            log.warn("Unable to obtain HttpMethod's response data stream", e);
        }
        try {
            httpMethod.getEntity().getContent().close();
        } catch (Exception ex) {}
        this.inputStream = new ByteArrayInputStream(new byte[] {}); // Empty input stream;
    }
}
项目:JZONbie    文件:ApacheJzonbieRequestFactoryTest.java   
@Test
public void createPrimeZombieWithFileRequest() throws Exception {
    final File file = new File(getClass().getClassLoader().getResource("example-priming.json").getFile());

    final HttpUriRequest primeZombieRequest = requestFactory.createPrimeZombieWithFileRequest(file);

    assertThat(primeZombieRequest.getMethod()).isEqualTo("POST");
    assertThat(primeZombieRequest.getURI().toString()).isEqualTo(zombieBaseUrl);
    assertZombieHeader(primeZombieRequest, "zombie", "priming-file");

    final HttpEntityEnclosingRequest httpPost = (HttpEntityEnclosingRequest)primeZombieRequest;

    final String entityString = IOUtils.toString(httpPost.getEntity().getContent(), defaultCharset());
    final String fileString = IOUtils.toString(new FileInputStream(file), defaultCharset());

    assertThat(entityString).contains(fileString);
}
项目:dcos-commons    文件:SecretsClientTest.java   
@Test
public void testCreateValidRequest() throws IOException {
    when(mockStatusLine.getStatusCode()).thenReturn(201);

    client.create("scheduler-name/secret-name", PAYLOAD);
    ArgumentCaptor<HttpUriRequest> passedRequest = ArgumentCaptor.forClass(HttpUriRequest.class);
    verify(mockHttpClient).execute(passedRequest.capture(), Mockito.any(HttpContext.class));
    HttpUriRequest request = passedRequest.getValue();

    Assert.assertEquals(request.getMethod(), "PUT");
    Assert.assertEquals(request.getURI().getPath(), "/secrets/v1/secret/default/scheduler-name/secret-name");

    Assert.assertTrue(request instanceof HttpEntityEnclosingRequest);
    HttpEntity httpEntity = ((HttpEntityEnclosingRequest)request).getEntity();

    Assert.assertEquals(httpEntity.getContentType().getValue(), ContentType.APPLICATION_JSON.toString());

    ByteArrayOutputStream content = new ByteArrayOutputStream();
    httpEntity.writeTo(content);
    JSONObject jsonObject = new JSONObject(content.toString("UTF-8"));

    Assert.assertEquals(jsonObject.getString("value"), PAYLOAD.getValue());
    Assert.assertEquals(jsonObject.getString("author"), PAYLOAD.getAuthor());
    Assert.assertEquals(jsonObject.getString("description"), PAYLOAD.getDescription());
}
项目:dcos-commons    文件:SecretsClientTest.java   
@Test
public void testUpdate() throws IOException {
    when(mockStatusLine.getStatusCode()).thenReturn(204);
    client.update("scheduler-name/secret-name", PAYLOAD);

    ArgumentCaptor<HttpUriRequest> passedRequest = ArgumentCaptor.forClass(HttpUriRequest.class);
    verify(mockHttpClient).execute(passedRequest.capture(), Mockito.any(HttpContext.class));
    HttpUriRequest request = passedRequest.getValue();

    Assert.assertEquals(request.getMethod(), "PATCH");
    Assert.assertEquals(request.getURI().getPath(), "/secrets/v1/secret/default/scheduler-name/secret-name");

    Assert.assertTrue(request instanceof HttpEntityEnclosingRequest);
    HttpEntity httpEntity = ((HttpEntityEnclosingRequest)request).getEntity();

    Assert.assertEquals(httpEntity.getContentType().getValue(), ContentType.APPLICATION_JSON.toString());

    ByteArrayOutputStream content = new ByteArrayOutputStream();
    httpEntity.writeTo(content);
    JSONObject jsonObject = new JSONObject(content.toString("UTF-8"));

    Assert.assertEquals(jsonObject.getString("value"), PAYLOAD.getValue());
    Assert.assertEquals(jsonObject.getString("author"), PAYLOAD.getAuthor());
    Assert.assertEquals(jsonObject.getString("description"), PAYLOAD.getDescription());
}
项目:put-it-to-rest    文件:GzippingHttpRequestInterceptor.java   
@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    if (request instanceof HttpEntityEnclosingRequest) {
        final HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
        final HttpEntity entity = entityRequest.getEntity();
        if (entity != null) {
            final GzipCompressingEntity zippedEntity = new GzipCompressingEntity(entity);
            entityRequest.setEntity(zippedEntity);

            request.removeHeaders(HTTP.CONTENT_ENCODING);
            request.addHeader(zippedEntity.getContentEncoding());

            request.removeHeaders(HTTP.CONTENT_LEN);

            request.removeHeaders(HTTP.TRANSFER_ENCODING);
            request.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING);
        }

    }
}
项目:product-ei    文件:SimpleHttpClient.java   
/**
 * Send a HTTP POST request to the specified URL
 *
 * @param url         Target endpoint URL
 * @param headers     Any HTTP headers that should be added to the request
 * @param payload     Content payload that should be sent
 * @param contentType Content-type of the request
 * @return Returned HTTP response
 * @throws IOException If an error occurs while making the invocation
 */
public HttpResponse doPost(String url, final Map<String, String> headers,
                           final String payload, String contentType) throws IOException {
    HttpUriRequest request = new HttpPost(url);
    setHeaders(headers, request);
    HttpEntityEnclosingRequest entityEncReq = (HttpEntityEnclosingRequest) request;
    final boolean zip = headers != null && "gzip".equals(headers.get(HttpHeaders.CONTENT_ENCODING));

    EntityTemplate ent = new EntityTemplate(new ContentProducer() {
        public void writeTo(OutputStream outputStream) throws IOException {
            OutputStream out = outputStream;
            if (zip) {
                out = new GZIPOutputStream(outputStream);
            }
            out.write(payload.getBytes());
            out.flush();
            out.close();
        }
    });
    ent.setContentType(contentType);
    if (zip) {
        ent.setContentEncoding("gzip");
    }
    entityEncReq.setEntity(ent);
    return client.execute(request);
}
项目:product-ei    文件:SimpleHttpClient.java   
/**
 * Send a HTTP PATCH request to the specified URL
 *
 * @param url         Target endpoint URL
 * @param headers     Any HTTP headers that should be added to the request
 * @param payload     Content payload that should be sent
 * @param contentType Content-type of the request
 * @return Returned HTTP response
 * @throws IOException If an error occurs while making the invocation
 */
public HttpResponse doPatch(String url, final Map<String, String> headers,
                            final String payload, String contentType) throws IOException {
    HttpUriRequest request = new HttpPatch(url);
    setHeaders(headers, request);
    HttpEntityEnclosingRequest entityEncReq = (HttpEntityEnclosingRequest) request;
    final boolean zip = headers != null && "gzip".equals(headers.get(HttpHeaders.CONTENT_ENCODING));

    EntityTemplate ent = new EntityTemplate(new ContentProducer() {
        public void writeTo(OutputStream outputStream) throws IOException {
            OutputStream out = outputStream;
            if (zip) {
                out = new GZIPOutputStream(outputStream);
            }
            out.write(payload.getBytes());
            out.flush();
            out.close();
        }
    });
    ent.setContentType(contentType);
    if (zip) {
        ent.setContentEncoding("gzip");
    }
    entityEncReq.setEntity(ent);
    return client.execute(request);
}
项目:product-ei    文件:SimpleHttpClient.java   
/**
 * Send a HTTP DELETE request with entity body to the specified URL
 *
 * @param url         Target endpoint URL
 * @param headers     Any HTTP headers that should be added to the request
 * @return Returned HTTP response
 * @throws IOException If an error occurs while making the invocation
 */
public HttpResponse doDeleteWithPayload(String url, final Map<String, String> headers,
        final String payload, String contentType) throws IOException {

    boolean zip = false;
    HttpUriRequest request = new HttpDeleteWithEntity(url);
    setHeaders(headers, request);
    HttpEntityEnclosingRequest entityEncReq = (HttpEntityEnclosingRequest) request;

    //check if content encoding required
    if (headers != null && "gzip".equals(headers.get(HttpHeaders.CONTENT_ENCODING))) {
        zip = true;
    }

    EntityTemplate ent = new EntityTemplate(new EntityContentProducer(payload, zip));
    ent.setContentType(contentType);

    if (zip) {
        ent.setContentEncoding("gzip");
    }
    entityEncReq.setEntity(ent);
    return client.execute(request);
}
项目:product-ei    文件:SimpleHttpClient.java   
/**
 * Send a HTTP PUT request to the specified URL
 *
 * @param url         Target endpoint URL
 * @param headers     Any HTTP headers that should be added to the request
 * @param payload     Content payload that should be sent
 * @param contentType Content-type of the request
 * @return Returned HTTP response
 * @throws IOException If an error occurs while making the invocation
 */
public HttpResponse doPut(String url, final Map<String, String> headers,
                          final String payload, String contentType) throws IOException {
    HttpUriRequest request = new HttpPut(url);
    setHeaders(headers, request);
    HttpEntityEnclosingRequest entityEncReq = (HttpEntityEnclosingRequest) request;
    final boolean zip = headers != null && "gzip".equals(headers.get(HttpHeaders.CONTENT_ENCODING));

    EntityTemplate ent = new EntityTemplate(new ContentProducer() {
        public void writeTo(OutputStream outputStream) throws IOException {
            OutputStream out = outputStream;
            if (zip) {
                out = new GZIPOutputStream(outputStream);
            }
            out.write(payload.getBytes());
            out.flush();
            out.close();
        }
    });
    ent.setContentType(contentType);
    if (zip) {
        ent.setContentEncoding("gzip");
    }
    entityEncReq.setEntity(ent);
    return client.execute(request);
}
项目:paymax-server-sdk-java    文件:HttpRequestWrapper.java   
public HttpRequestWrapper(HttpRequestBase originalRequest)
        throws IllegalStateException, IOException {
    this.originalRequest = originalRequest;
    HttpEntity entity = null;
    if (originalRequest instanceof HttpEntityEnclosingRequest
            && (entity = ((HttpEntityEnclosingRequest) originalRequest)
            .getEntity()) != null) {
        body = IOUtils.toByteArray(entity.getContent());
        this.contentType = entity.getContentType() == null ? "" : entity
                .getContentType().getValue();
        this.contentLength = String.valueOf(body.length);

        ByteArrayEntity newEntity = new ByteArrayEntity(body);
        newEntity.setContentType(entity.getContentType());
        ((HttpEntityEnclosingRequest) originalRequest).setEntity(newEntity);
    } else {
        body = new byte[0];
        contentType = "";
        contentLength = "";
    }
}
项目:Android_CCTV    文件:CustomHttpServer.java   
public void handle(HttpRequest request, HttpResponse response, HttpContext arg2) throws HttpException, IOException {

            if (request.getRequestLine().getMethod().equals("POST")) {

                // Retrieve the POST content
                HttpEntityEnclosingRequest post = (HttpEntityEnclosingRequest) request;
                byte[] entityContent = EntityUtils.toByteArray(post.getEntity());
                String content = new String(entityContent, Charset.forName("UTF-8"));

                // Execute the request
                final String json = RequestHandler.handle(content);

                // Return the response
                EntityTemplate body = new EntityTemplate(new ContentProducer() {
                    public void writeTo(final OutputStream outstream) throws IOException {
                        OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                        writer.write(json);
                        writer.flush();
                    }
                });
                response.setStatusCode(HttpStatus.SC_OK);
                body.setContentType("application/json; charset=UTF-8");
                response.setEntity(body);
            }

        }
项目:yarpc-java    文件:HttpConnectionReuseTest.java   
private void makeRequest(HttpClientConnection conn, String body, Map<String, String> headers)
    throws IOException, HttpException {
  HttpEntityEnclosingRequest req = new HttpPost("/");
  req.setHeaders(
      new Header[] {
        new BasicHeader(HeaderMapper.SERVICE, SERVICE),
        new BasicHeader(HeaderMapper.PROCEDURE, ECHO_PROCEDURE),
        new BasicHeader(HeaderMapper.CALLER, CLIENT),
        new BasicHeader(HeaderMapper.ENCODING, RawEncoding.ENCODING),
        new BasicHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(body.length()))
      });
  headers.forEach(req::setHeader);
  req.setEntity(new ByteArrayEntity(body.getBytes(Charsets.UTF_8)));
  conn.sendRequestHeader(req);
  conn.sendRequestEntity(req);
  conn.flush();

  HttpResponse res = conn.receiveResponseHeader();
  assertEquals(HttpStatus.SC_OK, res.getStatusLine().getStatusCode());

  conn.receiveResponseEntity(res);
  String echo = EntityUtils.toString(res.getEntity(), Charsets.UTF_8);
  assertEquals(body, echo);
}
项目:purecloud-iot    文件:RequestProtocolCompliance.java   
/**
 * If the {@link HttpRequest} is non-compliant but 'fixable' we go ahead and
 * fix the request here.
 *
 * @param request the request to check for compliance
 * @throws ClientProtocolException when we have trouble making the request compliant
 */
public void makeRequestCompliant(final HttpRequestWrapper request)
    throws ClientProtocolException {

    if (requestMustNotHaveEntity(request)) {
        ((HttpEntityEnclosingRequest) request).setEntity(null);
    }

    verifyRequestWithExpectContinueFlagHas100continueHeader(request);
    verifyOPTIONSRequestWithBodyHasContentType(request);
    decrementOPTIONSMaxForwardsIfGreaterThen0(request);
    stripOtherFreshnessDirectivesWithNoCache(request);

    if (requestVersionIsTooLow(request)
            || requestMinorVersionIsTooHighMajorVersionsMatch(request)) {
        request.setProtocolVersion(HttpVersion.HTTP_1_1);
    }
}
项目:purecloud-iot    文件:TestDigestScheme.java   
@Test
public void testDigestAuthenticationQopAuthOrAuthIntNonRepeatableEntity() throws Exception {
    final String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", " +
            "qop=\"auth,auth-int\"";
    final Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
    final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("Post", "/");
    request.setEntity(new InputStreamEntity(new ByteArrayInputStream(new byte[] {'a'}), -1));
    final Credentials cred = new UsernamePasswordCredentials("username","password");
    final DigestScheme authscheme = new DigestScheme();
    final HttpContext context = new BasicHttpContext();
    authscheme.processChallenge(authChallenge);
    final Header authResponse = authscheme.authenticate(cred, request, context);

    Assert.assertEquals("Post:/", authscheme.getA2());

    final Map<String, String> table = parseAuthResponse(authResponse);
    Assert.assertEquals("username", table.get("username"));
    Assert.assertEquals("realm1", table.get("realm"));
    Assert.assertEquals("/", table.get("uri"));
    Assert.assertEquals("auth", table.get("qop"));
    Assert.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
}
项目:purecloud-iot    文件:TestResponseProtocolCompliance.java   
@Test
public void consumesBodyOf100ContinueResponseIfItArrives() throws Exception {
    final HttpEntityEnclosingRequest req = new BasicHttpEntityEnclosingRequest("POST", "/", HttpVersion.HTTP_1_1);
    final int nbytes = 128;
    req.setHeader("Content-Length","" + nbytes);
    req.setHeader("Content-Type", "application/octet-stream");
    final HttpEntity postBody = new ByteArrayEntity(HttpTestUtils.getRandomBytes(nbytes));
    req.setEntity(postBody);
    final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(req);

    final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_CONTINUE, "Continue");
    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);
}
项目:purecloud-iot    文件:TestCacheInvalidator.java   
@Test
public void testInvalidatesUrisInContentLocationHeadersOnPUTs() throws Exception {
    final HttpEntityEnclosingRequest putRequest = new BasicHttpEntityEnclosingRequest("PUT","/",HTTP_1_1);
    putRequest.setEntity(HttpTestUtils.makeBody(128));
    putRequest.setHeader("Content-Length","128");

    final String contentLocation = "http://foo.example.com/content";
    putRequest.setHeader("Content-Location", contentLocation);

    final String theUri = "http://foo.example.com:80/";
    cacheEntryHasVariantMap(new HashMap<String,String>());

    cacheReturnsEntryForUri(theUri);

    impl.flushInvalidatedCacheEntries(host, putRequest);

    verify(mockEntry).getVariantMap();
    verify(mockStorage).getEntry(theUri);
    verify(mockStorage).removeEntry(theUri);
    verify(mockStorage).removeEntry("http://foo.example.com:80/content");
}
项目:purecloud-iot    文件:TestCacheInvalidator.java   
@Test
public void testInvalidatesUrisInLocationHeadersOnPUTs() throws Exception {
    final HttpEntityEnclosingRequest putRequest = new BasicHttpEntityEnclosingRequest("PUT","/",HTTP_1_1);
    putRequest.setEntity(HttpTestUtils.makeBody(128));
    putRequest.setHeader("Content-Length","128");

    final String contentLocation = "http://foo.example.com/content";
    putRequest.setHeader("Location",contentLocation);

    final String theUri = "http://foo.example.com:80/";
    cacheEntryHasVariantMap(new HashMap<String,String>());

    cacheReturnsEntryForUri(theUri);

    impl.flushInvalidatedCacheEntries(host, putRequest);

    verify(mockEntry).getVariantMap();
    verify(mockStorage).getEntry(theUri);
    verify(mockStorage).removeEntry(theUri);
    verify(mockStorage).removeEntry(cacheKeyGenerator.canonicalizeUri(contentLocation));
}
项目:purecloud-iot    文件:TestCacheInvalidator.java   
@Test
public void testInvalidatesRelativeUrisInContentLocationHeadersOnPUTs() throws Exception {
    final HttpEntityEnclosingRequest putRequest = new BasicHttpEntityEnclosingRequest("PUT","/",HTTP_1_1);
    putRequest.setEntity(HttpTestUtils.makeBody(128));
    putRequest.setHeader("Content-Length","128");

    final String relativePath = "/content";
    putRequest.setHeader("Content-Location",relativePath);

    final String theUri = "http://foo.example.com:80/";
    cacheEntryHasVariantMap(new HashMap<String,String>());

    cacheReturnsEntryForUri(theUri);

    impl.flushInvalidatedCacheEntries(host, putRequest);

    verify(mockEntry).getVariantMap();
    verify(mockStorage).getEntry(theUri);
    verify(mockStorage).removeEntry(theUri);
    verify(mockStorage).removeEntry("http://foo.example.com:80/content");
}
项目:purecloud-iot    文件:TestCacheInvalidator.java   
@Test
public void testDoesNotInvalidateUrisInContentLocationHeadersOnPUTsToDifferentHosts() throws Exception {
    final HttpEntityEnclosingRequest putRequest = new BasicHttpEntityEnclosingRequest("PUT","/",HTTP_1_1);
    putRequest.setEntity(HttpTestUtils.makeBody(128));
    putRequest.setHeader("Content-Length","128");

    final String contentLocation = "http://bar.example.com/content";
    putRequest.setHeader("Content-Location",contentLocation);

    final String theUri = "http://foo.example.com:80/";
    cacheEntryHasVariantMap(new HashMap<String,String>());

    cacheReturnsEntryForUri(theUri);

    impl.flushInvalidatedCacheEntries(host, putRequest);

    verify(mockEntry).getVariantMap();
    verify(mockStorage).getEntry(theUri);
    verify(mockStorage).removeEntry(theUri);
}
项目:purecloud-iot    文件:TestDigestScheme.java   
@Test
public void testDigestAuthenticationQopAuthInt() throws Exception {
    final String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", " +
            "qop=\"auth,auth-int\"";
    final Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
    final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("Post", "/");
    request.setEntity(new StringEntity("abc\u00e4\u00f6\u00fcabc", HTTP.DEF_CONTENT_CHARSET));
    final Credentials cred = new UsernamePasswordCredentials("username","password");
    final DigestScheme authscheme = new DigestScheme();
    final HttpContext context = new BasicHttpContext();
    authscheme.processChallenge(authChallenge);
    final Header authResponse = authscheme.authenticate(cred, request, context);

    Assert.assertEquals("Post:/:acd2b59cd01c7737d8069015584c6cac", authscheme.getA2());

    final Map<String, String> table = parseAuthResponse(authResponse);
    Assert.assertEquals("username", table.get("username"));
    Assert.assertEquals("realm1", table.get("realm"));
    Assert.assertEquals("/", table.get("uri"));
    Assert.assertEquals("auth-int", table.get("qop"));
    Assert.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
}
项目:purecloud-iot    文件:RequestExpectContinue.java   
@Override
public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {
    Args.notNull(request, "HTTP request");

    if (!request.containsHeader(HTTP.EXPECT_DIRECTIVE)) {
        if (request instanceof HttpEntityEnclosingRequest) {
            final ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
            final HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
            // Do not send the expect header if request body is known to be empty
            if (entity != null
                    && entity.getContentLength() != 0 && !ver.lessEquals(HttpVersion.HTTP_1_0)) {
                final HttpClientContext clientContext = HttpClientContext.adapt(context);
                final RequestConfig config = clientContext.getRequestConfig();
                if (config.isExpectContinueEnabled()) {
                    request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE);
                }
            }
        }
    }
}
项目:asch-java    文件:REST.java   
protected static void addCustomeHeads(Map<String, String> heads, HttpEntityEnclosingRequest request) {
    if (null == heads ) return;

    for (Map.Entry<String, String> entry : heads.entrySet()){
        request.setHeader(entry.getKey(), entry.getValue());
    }
}
项目:GitHub    文件:OkApacheClient.java   
private static Request transformRequest(HttpRequest request) {
  Request.Builder builder = new Request.Builder();

  RequestLine requestLine = request.getRequestLine();
  String method = requestLine.getMethod();
  builder.url(requestLine.getUri());

  String contentType = null;
  for (Header header : request.getAllHeaders()) {
    String name = header.getName();
    if ("Content-Type".equalsIgnoreCase(name)) {
      contentType = header.getValue();
    } else {
      builder.header(name, header.getValue());
    }
  }

  RequestBody body = null;
  if (request instanceof HttpEntityEnclosingRequest) {
    HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
    if (entity != null) {
      // Wrap the entity in a custom Body which takes care of the content, length, and type.
      body = new HttpEntityBody(entity, contentType);

      Header encoding = entity.getContentEncoding();
      if (encoding != null) {
        builder.header(encoding.getName(), encoding.getValue());
      }
    } else {
      body = Util.EMPTY_REQUEST;
    }
  }
  builder.method(method, body);

  return builder.build();
}