org.apache.http.HttpEntityEnclosingRequest Java Examples

The following examples show how to use org.apache.http.HttpEntityEnclosingRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SimpleHttpClient.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #2
Source File: HttpComponentsAsyncClientHttpRequest.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: ApacheHttpRequest.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
  HttpUriRequest request = getRawRequest();
  StringBuilder outBuffer = new StringBuilder();
  String endl = "\n";
  outBuffer.append("ApacheHttpRequest Info").append(endl);
  outBuffer.append("type: HttpUriRequest").append(endl);
  outBuffer.append("uri: ").append(request.getURI().toString()).append(endl);
  outBuffer.append("headers: ");
  Arrays.stream(request.getAllHeaders()).forEach(header ->
      outBuffer.append("[").append(header.getName()).append(":").append(header.getValue()).append("] ")
  );
  outBuffer.append(endl);

  if (request instanceof HttpEntityEnclosingRequest) {
    try {
      String body = EntityUtils.toString(((HttpEntityEnclosingRequest) request).getEntity());
      outBuffer.append("body: ").append(body).append(endl);
    } catch (IOException e) {
      outBuffer.append("body: ").append(e.getMessage()).append(endl);
    }
  }
  return outBuffer.toString();
}
 
Example #4
Source File: RESTClient.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * Sends 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);
    HTTPUtils.setHTTPHeaders(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 httpclient.execute(request);
}
 
Example #5
Source File: EntityForwardingRedirectStrategy.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Override
public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws ProtocolException
{
    final String method = request.getRequestLine().getMethod();
    HttpUriRequest redirect = super.getRedirect(request, response, context);
    if (HttpPost.METHOD_NAME.equalsIgnoreCase(method))
    {
        HttpPost httpPostRequest = new HttpPost(redirect.getURI());
        if (request instanceof HttpEntityEnclosingRequest)
        {
            httpPostRequest.setEntity(((HttpEntityEnclosingRequest) request).getEntity());
        }
        return httpPostRequest;
    }
    return redirect;
}
 
Example #6
Source File: BceHttpClient.java    From bce-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Get delay time before next retry.
 *
 * @param method The current HTTP method being executed.
 * @param exception The client/service exception from the failed request.
 * @param attempt The number of times the current request has been attempted.
 * @param retryPolicy The retryPolicy being used.
 * @return The deley time before next retry.
 */
protected long getDelayBeforeNextRetryInMillis(HttpRequestBase method, BceClientException exception, int attempt,
        RetryPolicy retryPolicy) {
    int retries = attempt - 1;

    int maxErrorRetry = retryPolicy.getMaxErrorRetry();

    // Immediately fails when it has exceeds the max retry count.
    if (retries >= maxErrorRetry) {
        return -1;
    }

    // Never retry on requests containing non-repeatable entity
    if (method instanceof HttpEntityEnclosingRequest) {
        HttpEntity entity = ((HttpEntityEnclosingRequest) method).getEntity();
        if (entity != null && !entity.isRepeatable()) {
            logger.debug("Entity not repeatable, stop retrying");
            return -1;
        }
    }

    return Math.min(retryPolicy.getMaxDelayInMillis(),
            retryPolicy.getDelayBeforeNextRetryInMillis(exception, retries));
}
 
Example #7
Source File: SimpleHttpClient.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #8
Source File: HTTPClientUtil.java    From rest-client with Apache License 2.0 6 votes vote down vote up
static String getHTTPRequestTrace(HttpRequest request) {
    StringBuilder sb = new StringBuilder();
    sb.append(request.getRequestLine());
    sb.append('\n');
    for (Header h : request.getAllHeaders()) {
        sb.append(h.getName()).append(": ").append(h.getValue()).append('\n');
    }
    sb.append('\n');

    // Check if the request is POST or PUT
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest r = (HttpEntityEnclosingRequest) request;
        HttpEntity e = r.getEntity();
        if (e != null) {
            appendHttpEntity(sb, e);
        }
    }
    return sb.toString();
}
 
Example #9
Source File: ApacheHttpClientEdgeGridRequestSigner.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 6 votes vote down vote up
private byte[] serializeContent(HttpRequest request) {
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return new byte[]{};
    }

    final HttpEntityEnclosingRequest entityWithRequest = (HttpEntityEnclosingRequest) request;
    HttpEntity entity = entityWithRequest.getEntity();
    if (entity == null) {
        return new byte[]{};
    }

    try {
        // Buffer non-repeatable entities
        if (!entity.isRepeatable()) {
            entityWithRequest.setEntity(new BufferedHttpEntity(entity));
        }
        return EntityUtils.toByteArray(entityWithRequest.getEntity());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #10
Source File: HttpClientUtil.java    From AndroidRobot with Apache License 2.0 6 votes vote down vote up
public boolean retryRequest(IOException exception, int executionCount,  
        HttpContext context) {  
    // 设置恢复策略,在发生异常时候将自动重试3次  
    if (executionCount >= 3) {  
        // 如果连接次数超过了最大值则停止重试  
        return false;  
    }  
    if (exception instanceof NoHttpResponseException) {  
        // 如果服务器连接失败重试  
        return true;  
    }  
    if (exception instanceof SSLHandshakeException) {  
        // 不要重试ssl连接异常  
        return false;  
    }  
    HttpRequest request = (HttpRequest) context  
            .getAttribute(ExecutionContext.HTTP_REQUEST);  
    boolean idempotent = (request instanceof HttpEntityEnclosingRequest);  
    if (!idempotent) {  
        // 重试,如果请求是考虑幂等  
        return true;  
    }  
    return false;  
}
 
Example #11
Source File: AWSRequestSigningApacheInterceptorTest.java    From aws-request-signing-apache-interceptor with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #12
Source File: Solr6Index.java    From atlas with Apache License 2.0 6 votes vote down vote up
private void configureSolrClientsForKerberos() throws PermanentBackendException {
    String kerberosConfig = System.getProperty("java.security.auth.login.config");
    if(kerberosConfig == null) {
        throw new PermanentBackendException("Unable to configure kerberos for solr client. System property 'java.security.auth.login.config' is not set.");
    }
    logger.debug("Using kerberos configuration file located at '{}'.", kerberosConfig);
    try(Krb5HttpClientBuilder krbBuild = new Krb5HttpClientBuilder()) {

        SolrHttpClientBuilder kb = krbBuild.getBuilder();
        HttpClientUtil.setHttpClientBuilder(kb);
        HttpRequestInterceptor bufferedEntityInterceptor = new HttpRequestInterceptor() {
            @Override
            public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
                if(request instanceof HttpEntityEnclosingRequest) {
                    HttpEntityEnclosingRequest enclosingRequest = ((HttpEntityEnclosingRequest) request);
                    HttpEntity requestEntity = enclosingRequest.getEntity();
                    enclosingRequest.setEntity(new BufferedHttpEntity(requestEntity));
                }
            }
        };
        HttpClientUtil.addRequestInterceptor(bufferedEntityInterceptor);

        HttpRequestInterceptor preemptiveAuth = new PreemptiveAuth(new KerberosScheme());
        HttpClientUtil.addRequestInterceptor(preemptiveAuth);
    }
}
 
Example #13
Source File: CustomHttpServer.java    From spydroid-ipcamera with GNU General Public License v3.0 6 votes vote down vote up
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);
			}

		}
 
Example #14
Source File: AopHttpClient.java    From ArgusAPM with Apache License 2.0 6 votes vote down vote up
private static HttpRequest handleRequest(HttpHost host, HttpRequest request, NetInfo data) {
    RequestLine requestLine = request.getRequestLine();
    if (requestLine != null) {
        String uri = requestLine.getUri();
        int i = (uri != null) && (uri.length() >= 10) && (uri.substring(0, 10).indexOf("://") >= 0) ? 1 : 0;
        if ((i == 0) && (uri != null) && (host != null)) {
            String uriFromHost = host.toURI().toString();
            data.setURL(uriFromHost + ((uriFromHost.endsWith("/")) || (uri.startsWith("/")) ? "" : "/") + uri);
        } else if (i != 0) {
            data.setURL(uri);
        }
    }
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
        if (entityRequest.getEntity() != null) {
            entityRequest.setEntity(new AopHttpRequestEntity(entityRequest.getEntity(), data));
        }
        return entityRequest;
    }
    return request;
}
 
Example #15
Source File: HttpComponentsAsyncClientHttpRequest.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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);
	}

	HttpResponseFutureCallback callback = new HttpResponseFutureCallback(this.httpRequest);
	Future<HttpResponse> futureResponse = this.httpClient.execute(this.httpRequest, this.httpContext, callback);
	return new ClientHttpResponseFuture(futureResponse, callback);
}
 
Example #16
Source File: StringPayloadOf.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Ctor.
 *
 * @param request The http request
 * @throws IllegalStateException if the request's payload cannot be read
 */
public StringPayloadOf(final HttpRequest request) {
    try {
        if (request instanceof HttpEntityEnclosingRequest) {
            this.stringPayload = EntityUtils.toString(
                ((HttpEntityEnclosingRequest) request).getEntity()
            );
        } else {
            this.stringPayload = "";
        }
    } catch (final IOException ex) {
        throw new IllegalStateException(
            "Cannot read request payload", ex
        );
    }
}
 
Example #17
Source File: SimpleHttpFetcher.java    From ache with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #18
Source File: PayloadOf.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Ctor.
 * 
 * @param request The http request
 * @throws IllegalStateException if the request's payload cannot be read
 */
PayloadOf(final HttpRequest request) {
    super(() -> {
        try {
            final JsonObject body;
            if (request instanceof HttpEntityEnclosingRequest) {
                body = Json.createReader(
                    ((HttpEntityEnclosingRequest) request).getEntity()
                        .getContent()
                ).readObject();
            } else {
                body =  Json.createObjectBuilder().build();
            }
            return body;
        } catch (final IOException ex) {
            throw new IllegalStateException(
                "Cannot read request payload", ex
            );
        }
    });
}
 
Example #19
Source File: TestUtils.java    From phabricator-jenkins-plugin with MIT License 6 votes vote down vote up
public static HttpRequestHandler makeHttpHandler(
        final int statusCode, final String body,
        final List<String> requestBodies) {
    return new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException,
                IOException {
            response.setStatusCode(statusCode);
            response.setEntity(new StringEntity(body));

            if (request instanceof HttpEntityEnclosingRequest) {
                HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
                requestBodies.add(EntityUtils.toString(entity));
            } else {
                requestBodies.add("");
            }
        }
    };
}
 
Example #20
Source File: RESTClient.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Prepares a HttpUriRequest to be sent.
 *
 * @param headers HTTP headers to be set as a MAP <Header name, Header value>
 * @param payload Final payload to be sent
 * @param contentType Content-type (i.e application/json)
 * @param request HttpUriRequest request to be prepared
 */
private void prepareRequest(Map<String, String> headers, final String payload, String contentType,
                            HttpUriRequest request) {
    HTTPUtils.setHTTPHeaders(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);
}
 
Example #21
Source File: LtiOauthSigner.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private String getRequestBody(HttpRequest req) throws IOException {
    if(req instanceof HttpEntityEnclosingRequest){
        HttpEntity body = ((HttpEntityEnclosingRequest) req).getEntity();
        if(body == null) {
            return "";
        } else {
            return IOUtils.toString(body.getContent());
        }
    } else {
        // requests with no entity have an empty string as the body
        return "";
    }
}
 
Example #22
Source File: LibRequestDirector.java    From YiBo with Apache License 2.0 5 votes vote down vote up
private RequestWrapper wrapRequest(
        final HttpRequest request) throws ProtocolException {
    if (request instanceof HttpEntityEnclosingRequest) {
        return new EntityEnclosingRequestWrapper(
                (HttpEntityEnclosingRequest) request);
    } else {
        return new RequestWrapper(
                request);
    }
}
 
Example #23
Source File: SpecialCharacterTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
public void requestReceived(HttpRequest request) {
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
        try {
            InputStream in = entity.getContent();
            String inputString = IOUtils.toString(in, "UTF-8");
            payload = inputString;
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
 
Example #24
Source File: AopHttpClient.java    From ArgusAPM with Apache License 2.0 5 votes vote down vote up
private static HttpUriRequest handleRequest(HttpUriRequest request, NetInfo data) {
    data.setURL(request.getURI().toString());
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
        if (entityRequest.getEntity() != null) {
            entityRequest.setEntity(new AopHttpRequestEntity(entityRequest.getEntity(), data));
        }
        return (HttpUriRequest) entityRequest;
    }
    return request;
}
 
Example #25
Source File: RtImagesTestCase.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * RtImages can import images from tar successfully.
 * @throws Exception If something goes wrong
 */
@Test
public void importFromTar() throws Exception{
    new ListedImages(
        new AssertRequest(
            new Response(HttpStatus.SC_OK),
            new Condition(
                "import() must send a POST request",
                req -> "POST".equals(req.getRequestLine().getMethod())
            ),
            new Condition(
                "import() resource URL must be '/images/load'",
                req -> req.getRequestLine()
                    .getUri().endsWith("/images/load")
            ),
            new Condition(
                "import() body must contain a tar archive containing image",
                req -> {
                    boolean condition = false;
                    try{
                        condition =
                            EntityUtils.toByteArray(
                                ((HttpEntityEnclosingRequest) req)
                                .getEntity()
                            ).length > 0;
                    } catch (final IOException error){
                        condition = false;
                    }
                    return condition;
                }
            )
        ),
        URI.create("http://localhost/images"),
        DOCKER
        ).importFromTar(
            this.getClass().getResource("/images.tar.txt").getFile());
}
 
Example #26
Source File: HttpComponentsStreamingClientHttpRequest.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException {
	HttpComponentsClientHttpRequest.addHeaders(this.httpRequest, headers);

	if (this.httpRequest instanceof HttpEntityEnclosingRequest && body != null) {
		HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) this.httpRequest;
		HttpEntity requestEntity = new StreamingHttpEntity(getHeaders(), body);
		entityEnclosingRequest.setEntity(requestEntity);
	}

	HttpResponse httpResponse = this.httpClient.execute(this.httpRequest, this.httpContext);
	return new HttpComponentsClientHttpResponse(httpResponse);
}
 
Example #27
Source File: AbstractRefTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
protected HttpResponse callUri(
    final ODataHttpMethod httpMethod, final String uri,
    final String additionalHeader, final String additionalHeaderValue,
    final String requestBody, final String requestContentType,
    final HttpStatusCodes expectedStatusCode) throws Exception {

  HttpRequestBase request =
      httpMethod == ODataHttpMethod.GET ? new HttpGet() :
          httpMethod == ODataHttpMethod.DELETE ? new HttpDelete() :
              httpMethod == ODataHttpMethod.POST ? new HttpPost() :
                  httpMethod == ODataHttpMethod.PUT ? new HttpPut() : new HttpPatch();
  request.setURI(URI.create(getEndpoint() + uri));
  if (additionalHeader != null) {
    request.addHeader(additionalHeader, additionalHeaderValue);
  }
  if (requestBody != null) {
    ((HttpEntityEnclosingRequest) request).setEntity(new StringEntity(requestBody));
    request.setHeader(HttpHeaders.CONTENT_TYPE, requestContentType);
  }

  final HttpResponse response = getHttpClient().execute(request);

  assertNotNull(response);
  assertEquals(expectedStatusCode.getStatusCode(), response.getStatusLine().getStatusCode());

  if (expectedStatusCode == HttpStatusCodes.OK) {
    assertNotNull(response.getEntity());
    assertNotNull(response.getEntity().getContent());
  } else if (expectedStatusCode == HttpStatusCodes.CREATED) {
    assertNotNull(response.getEntity());
    assertNotNull(response.getEntity().getContent());
    assertNotNull(response.getFirstHeader(HttpHeaders.LOCATION));
  } else if (expectedStatusCode == HttpStatusCodes.NO_CONTENT) {
    assertTrue(response.getEntity() == null || response.getEntity().getContent() == null);
  }

  return response;
}
 
Example #28
Source File: PreemptiveAuthHttpClientConnection.java    From git-client-plugin with MIT License 5 votes vote down vote up
private void execute() throws IOException, ClientProtocolException {
    if (resp == null)
        if (entity != null) {
            if (req instanceof HttpEntityEnclosingRequest) {
                HttpEntityEnclosingRequest eReq = (HttpEntityEnclosingRequest) req;
                eReq.setEntity(entity);
            }
            resp = getClient().execute(req);
            entity.getBuffer().close();
            entity = null;
        } else
            resp = getClient().execute(req);
}
 
Example #29
Source File: HttpClient4EntityExtractor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public String getEntity(HttpRequest httpRequest) {
    if (httpRequest instanceof HttpEntityEnclosingRequest) {
        final HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) httpRequest;
        try {
            final HttpEntity entity = entityRequest.getEntity();
            if (entity != null && entity.isRepeatable() && entity.getContentLength() > 0) {
                return entityUtilsToString(entity, Charsets.UTF_8_NAME, 1024);
            }
        } catch (Exception e) {
            logger.debug("Failed to get entity. httpRequest={}", httpRequest, e);
        }
    }
    return null;
}
 
Example #30
Source File: ElasticsearchTransport.java    From calcite with Apache License 2.0 5 votes vote down vote up
private Response applyInternal(final HttpRequest request)
    throws IOException  {

  Objects.requireNonNull(request, "request");
  final HttpEntity entity = request instanceof HttpEntityEnclosingRequest
      ? ((HttpEntityEnclosingRequest) request).getEntity() : null;

  final Request r = new Request(
      request.getRequestLine().getMethod(),
      request.getRequestLine().getUri());
  r.setEntity(entity);
  final Response response = restClient.performRequest(r);

  final String payload = entity != null && entity.isRepeatable()
      ? EntityUtils.toString(entity) : "<empty>";

  if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
    final String error = EntityUtils.toString(response.getEntity());

    final String message = String.format(Locale.ROOT,
        "Error while querying Elastic (on %s/%s) status: %s\nPayload:\n%s\nError:\n%s\n",
        response.getHost(), response.getRequestLine(),
        response.getStatusLine(), payload, error);
    throw new RuntimeException(message);
  }

  return response;
}