Example usage for org.apache.http.client.methods HttpUriRequest getMethod

List of usage examples for org.apache.http.client.methods HttpUriRequest getMethod

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpUriRequest getMethod.

Prototype

String getMethod();

Source Link

Document

Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other.

Usage

From source file:org.elasticsearch.client.RequestLoggerTests.java

public void testTraceRequest() throws IOException, URISyntaxException {
    HttpHost host = new HttpHost("localhost", 9200, randomBoolean() ? "http" : "https");
    String expectedEndpoint = "/index/type/_api";
    URI uri;//  w ww  .j  a v a  2  s  .  c o  m
    if (randomBoolean()) {
        uri = new URI(expectedEndpoint);
    } else {
        uri = new URI("index/type/_api");
    }
    HttpUriRequest request = randomHttpRequest(uri);
    String expected = "curl -iX " + request.getMethod() + " '" + host + expectedEndpoint + "'";
    boolean hasBody = request instanceof HttpEntityEnclosingRequest && randomBoolean();
    String requestBody = "{ \"field\": \"value\" }";
    if (hasBody) {
        expected += " -d '" + requestBody + "'";
        HttpEntityEnclosingRequest enclosingRequest = (HttpEntityEnclosingRequest) request;
        HttpEntity entity;
        switch (randomIntBetween(0, 4)) {
        case 0:
            entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
            break;
        case 1:
            entity = new InputStreamEntity(
                    new ByteArrayInputStream(requestBody.getBytes(StandardCharsets.UTF_8)),
                    ContentType.APPLICATION_JSON);
            break;
        case 2:
            entity = new NStringEntity(requestBody, ContentType.APPLICATION_JSON);
            break;
        case 3:
            entity = new NByteArrayEntity(requestBody.getBytes(StandardCharsets.UTF_8),
                    ContentType.APPLICATION_JSON);
            break;
        case 4:
            // Evil entity without a charset
            entity = new StringEntity(requestBody, ContentType.create("application/json", (Charset) null));
            break;
        default:
            throw new UnsupportedOperationException();
        }
        enclosingRequest.setEntity(entity);
    }
    String traceRequest = RequestLogger.buildTraceRequest(request, host);
    assertThat(traceRequest, equalTo(expected));
    if (hasBody) {
        //check that the body is still readable as most entities are not repeatable
        String body = EntityUtils.toString(((HttpEntityEnclosingRequest) request).getEntity(),
                StandardCharsets.UTF_8);
        assertThat(body, equalTo(requestBody));
    }
}

From source file:io.wcm.caravan.io.http.impl.RequestUtilTest.java

@Test
public void testBuildHttpRequest_Post() throws ParseException, IOException {
    RequestTemplate template = new RequestTemplate().method("post").append("/path").body("string body");
    HttpUriRequest request = RequestUtil.buildHttpRequest("http://host", template.request());

    assertEquals("http://host/path", request.getURI().toString());
    assertEquals(HttpPost.METHOD_NAME, request.getMethod());

    HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
    assertEquals("string body", EntityUtils.toString(entityRequest.getEntity()));
}

From source file:io.wcm.caravan.io.http.impl.RequestUtilTest.java

@Test
public void testBuildHttpRequest_Put() throws IOException {
    byte[] data = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 };
    RequestTemplate template = new RequestTemplate().method("put").append("/path").body(data, null);
    HttpUriRequest request = RequestUtil.buildHttpRequest("http://host", template.request());

    assertEquals("http://host/path", request.getURI().toString());
    assertEquals(HttpPut.METHOD_NAME, request.getMethod());

    HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
    assertArrayEquals(data, EntityUtils.toByteArray(entityRequest.getEntity()));
}

From source file:io.wcm.caravan.io.http.impl.RequestUtilTest.java

@Test
public void testBuildHttpRequest_Get() {
    RequestTemplate template = new RequestTemplate().method("get").append("/path").header("header1", "value1")
            .header("header2", "value2", "value3");
    HttpUriRequest request = RequestUtil.buildHttpRequest("http://host", template.request());

    assertEquals("http://host/path", request.getURI().toString());
    assertEquals(HttpGet.METHOD_NAME, request.getMethod());

    Map<String, Collection<String>> expected = ImmutableMap.<String, Collection<String>>of("header1",
            ImmutableList.of("value1"), "header2", ImmutableList.of("value2", "value3"));
    assertEquals(expected, RequestUtil.toHeadersMap(request.getAllHeaders()));
}

From source file:com.cloud.utils.rest.HttpRequestMatcher.java

private boolean checkMethod(final HttpUriRequest actual) {
    if (wanted instanceof HttpUriRequest) {
        final String wantedMethod = ((HttpUriRequest) wanted).getMethod();
        final String actualMethod = actual.getMethod();
        return equalsString(wantedMethod, actualMethod);
    } else {//from  w w  w.java2 s. co m
        return wanted == actual;
    }
}

From source file:com.github.avarabyeu.restendpoint.http.DefaultErrorHandler.java

/**
 * Default implementation. May be overridden in subclasses<br>
 * Throws//from   w  ww .j  a  v  a 2s .  c om
 * {@link com.github.avarabyeu.restendpoint.http.exception.RestEndpointClientException}
 * for client exceptions and
 * {@link com.github.avarabyeu.restendpoint.http.exception.RestEndpointServerException}
 * for server exceptions<br>
 * <p>
 * Throwed exceptions may be overridden in handle* methods
 */
@Override
public void handle(HttpUriRequest rq, HttpResponse rs) throws RestEndpointIOException {
    if (!hasError(rs)) {
        return;
    }
    HttpMethod httpMethod = HttpMethod.valueOf(rq.getMethod());
    URI requestUri = rq.getURI();

    StatusType statusType = StatusType.valueOf(rs.getStatusLine().getStatusCode());
    int statusCode = rs.getStatusLine().getStatusCode();
    String statusMessage = rs.getStatusLine().getReasonPhrase();

    byte[] errorBody = getErrorBody(rs);

    switch (statusType) {
    case CLIENT_ERROR:
        handleClientError(requestUri, httpMethod, statusCode, statusMessage, errorBody);
    case SERVER_ERROR:
        handleServerError(requestUri, httpMethod, statusCode, statusMessage, errorBody);
    default:
        handleDefaultError(requestUri, httpMethod, statusCode, statusMessage, errorBody);
    }
}

From source file:com.vmware.photon.controller.client.RestClientTest.java

@Test
public void testPerformGet() {
    ArgumentCaptor<HttpUriRequest> argumentCaptor = setup(RestClient.Method.GET, null);

    HttpUriRequest request = argumentCaptor.getValue();
    assertNotNull(request);//w  ww.jav  a2 s.c o  m
    assertTrue(request.getMethod().equalsIgnoreCase(RestClient.Method.GET.toString()));
    assertEquals(request.getURI().toString(), uri);
}

From source file:com.vmware.photon.controller.client.RestClientTest.java

@Test
public void testPerformDelete() {
    ArgumentCaptor<HttpUriRequest> argumentCaptor = setup(RestClient.Method.DELETE, null);

    HttpUriRequest request = argumentCaptor.getValue();
    assertNotNull(request);/*from w w  w . jav  a 2  s.co  m*/
    assertTrue(request.getMethod().equalsIgnoreCase(RestClient.Method.DELETE.toString()));
    assertEquals(request.getURI().toString(), uri);
}

From source file:cn.edu.zzu.wemall.http.RetryHandler.java

@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    boolean retry = true;

    Boolean b = (Boolean) context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
    boolean sent = (b != null && b);

    if (executionCount > maxRetries) {
        // Do not retry if over max retry count
        retry = false;/*from  w w w.j  a va2s. c  o  m*/
    } else if (isInList(exceptionBlacklist, exception)) {
        // immediately cancel retry if the error is blacklisted
        retry = false;
    } else if (isInList(exceptionWhitelist, exception)) {
        // immediately retry if error is whitelisted
        retry = true;
    } else if (!sent) {
        // for most other errors, retry only if request hasn't been fully sent yet
        retry = true;
    }

    if (retry) {
        // resend all idempotent requests
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        if (currentReq == null) {
            return false;
        }
        String requestType = currentReq.getMethod();
        retry = !requestType.equals("POST");
    }

    if (retry) {
        SystemClock.sleep(retrySleepTimeMS);
    } else {
        exception.printStackTrace();
    }

    return retry;
}

From source file:org.elasticsearch.test.rest.client.http.HttpRequestBuilder.java

public HttpResponse execute() throws IOException {
    CloseableHttpResponse closeableHttpResponse = null;
    try {//from w  ww .  j  a  v  a  2s  . co  m
        HttpUriRequest httpUriRequest = buildRequest();
        if (logger.isTraceEnabled()) {
            StringBuilder stringBuilder = new StringBuilder(httpUriRequest.getMethod()).append(" ")
                    .append(httpUriRequest.getURI());
            if (Strings.hasLength(body)) {
                stringBuilder.append("\n").append(body);
            }
            logger.trace("sending request \n{}", stringBuilder.toString());
        }
        closeableHttpResponse = httpClient.execute(httpUriRequest);
        HttpResponse httpResponse = new HttpResponse(httpUriRequest, closeableHttpResponse);
        logger.trace("got response \n{}\n{}", closeableHttpResponse,
                httpResponse.hasBody() ? httpResponse.getBody() : "");
        return httpResponse;
    } finally {
        try {
            IOUtils.close(closeableHttpResponse);
        } catch (IOException e) {
            logger.error("error closing http response", e);
        }
    }
}