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:com.evrythng.java.wrapper.core.api.ApiCommand.java

private HttpResponse performRequest(final HttpClient client, final MethodBuilder<?> method,
        final Status expectedStatus) throws EvrythngException {

    HttpResponse response;//from   www . j a va 2s . c o m
    HttpUriRequest request = buildRequest(method);
    try {
        logger.debug(">> Executing request: [method={}, url={}]", request.getMethod(),
                request.getURI().toString());
        response = client.execute(request);
        logger.debug("<< Response received: [statusLine={}]", response.getStatusLine().toString());
    } catch (Exception e) {
        // Convert to custom exception:
        throw new EvrythngClientException(String.format("Unable to execute request: [uri=%s, cause=%s]",
                request.getURI(), e.getMessage()), e);
    }

    // Assert response status:
    Utils.assertStatus(response, expectedStatus);

    return response;
}

From source file:com.seleritycorp.common.base.http.client.HttpRequestTest.java

@Test
public void testSetUserAgentReset() throws Exception {
    replayAll();/*from ww  w. ja  v a2s .  c o m*/

    HttpRequest request = createHttpRequest("foo");
    HttpRequest requestAfterSetting1 = request.setUserAgent("foo1");
    HttpRequest requestAfterSetting2 = request.setUserAgent(null);
    HttpResponse response = request.execute();

    verifyAll();

    assertThat(request).isSameAs(requestAfterSetting1);
    assertThat(request).isSameAs(requestAfterSetting2);
    assertThat(response).isEqualTo(httpResponse);

    HttpUriRequest backendRequest = backendRequestCapture.getValue();
    assertThat(backendRequest.getMethod()).isEqualTo("GET");
    assertThat(backendRequest.getURI().toString()).isEqualTo("foo");
    assertThat(backendRequest.getHeaders("User-Agent")).hasSize(0);
}

From source file:com.shenit.commons.utils.HttpUtils.java

/**
 * ?/*  w  ww. ja  va  2s . c  o  m*/
 * 
 * @param req
 * @return
 */
public static String dumpRequest(HttpUriRequest req) {
    if (req == null)
        return null;
    char column = ':', rtn = '\n', space = ' ';
    StringBuilder builder = new StringBuilder(req.getMethod());
    builder.append(space).append(req.getURI()).append(space).append(req.getProtocolVersion()).append(rtn)
            .append(rtn);
    builder.append("HEADERS:\n");
    Header[] headers = req.getAllHeaders();
    int length = headers.length;
    for (int i = 0; i < length; i++) {
        builder.append(headers[i].getName()).append(column).append(headers[i].getValue()).append(rtn);
    }
    if (req instanceof HttpPost || req instanceof HttpPut) {
        builder.append(rtn);
        builder.append("BODY:\n");
        if (null != ((HttpPost) req).getEntity()) {
            BufferedReader reader = null;
            try {
                InputStreamReader isReader = new InputStreamReader(((HttpPost) req).getEntity().getContent());
                reader = new BufferedReader(isReader);
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            } catch (IllegalStateException | IOException e) {
                if (LOG.isWarnEnabled())
                    LOG.warn("[dumpRequest] Could not read request due to exception", e);
            } finally {
                if (reader != null)
                    try {
                        reader.close();
                    } catch (IOException e) {
                        if (LOG.isWarnEnabled())
                            LOG.warn("[dumpRequest] could not close reader due to exception", e);
                    }
            }
        }
    }
    return builder.toString();
}

From source file:com.seleritycorp.common.base.http.client.HttpRequestTest.java

@Test
public void testSetUserAgentOverwrite() throws Exception {
    replayAll();// ww w  .  jav  a 2s.  co m

    HttpRequest request = createHttpRequest("foo");
    HttpRequest requestAfterSetting1 = request.setUserAgent("foo1");
    HttpRequest requestAfterSetting2 = request.setUserAgent("foo2");
    HttpResponse response = request.execute();

    verifyAll();

    assertThat(request).isSameAs(requestAfterSetting1);
    assertThat(request).isSameAs(requestAfterSetting2);
    assertThat(response).isEqualTo(httpResponse);

    HttpUriRequest backendRequest = backendRequestCapture.getValue();
    assertThat(backendRequest.getMethod()).isEqualTo("GET");
    assertThat(backendRequest.getURI().toString()).isEqualTo("foo");
    assertThat(backendRequest.getHeaders("User-Agent")).hasSize(1);
    assertThat(backendRequest.getFirstHeader("User-Agent").getValue()).isEqualTo("foo2");
}

From source file:org.dasein.cloud.azure.tests.network.AzureIpAddressSupportTest.java

@Test
public void stopForwardToServerShouldPostCorrectRequestIfNoMatchEndpointFound()
        throws CloudException, InternalException {
    final AtomicInteger putCount = new AtomicInteger(0);
    new MockUp<CloseableHttpClient>() {
        @Mock(invocations = 2)//from w  w  w . ja v  a  2s  .c om
        public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException {
            if (request.getMethod().equals("GET")) {
                DaseinObjectToXmlEntity<PersistentVMRoleModel> daseinEntity = new DaseinObjectToXmlEntity<PersistentVMRoleModel>(
                        createPersistentVMRoleModelWithEndpoint());
                assertGet(request, EXPECTED_URL,
                        new Header[] { new BasicHeader("x-ms-version", "2012-03-01") });
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else if (request.getMethod().equals("PUT")) {
                putCount.incrementAndGet();
                PersistentVMRoleModel persistentVMRoleModel = createPersistentVMRoleModelWithEndpoint();
                assertPut(request, EXPECTED_URL, new Header[] { new BasicHeader("x-ms-version", "2012-03-01") },
                        persistentVMRoleModel);
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_ACCEPTED), null,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else {
                throw new IOException("Request is not mocked");
            }
        }
    };
    String ruleId = new AzureRuleIdParts(VM_ID, Protocol.TCP.toString(), String.valueOf(PRIVATE_PORT + 1))
            .toProviderId();
    ipAddressSupport.stopForwardToServer(ruleId, VM_ID);
    assertEquals("PUT count doesn't match", 1, putCount.get());
}

From source file:org.dasein.cloud.azure.tests.network.AzureIpAddressSupportTest.java

@Test
public void forwardShouldPostCorrectRequest() throws CloudException, InternalException {
    final AtomicInteger putCount = new AtomicInteger(0);
    new MockUp<CloseableHttpClient>() {
        @Mock(invocations = 2)/*www.  j a v  a2s.  c  om*/
        public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException {
            if (request.getMethod().equals("GET")) {
                DaseinObjectToXmlEntity<PersistentVMRoleModel> daseinEntity = new DaseinObjectToXmlEntity<PersistentVMRoleModel>(
                        createPersistentVMRoleModelWithoutEndpoint());
                assertGet(request, EXPECTED_URL,
                        new Header[] { new BasicHeader("x-ms-version", "2012-03-01") });
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else if (request.getMethod().equals("PUT")) {
                putCount.incrementAndGet();
                PersistentVMRoleModel persistentVMRoleModel = createPersistentVMRoleModelWithEndpoint();
                assertPut(request, EXPECTED_URL, new Header[] { new BasicHeader("x-ms-version", "2012-03-01") },
                        persistentVMRoleModel);
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_ACCEPTED), null,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else {
                throw new IOException("Request is not mocked");
            }
        }
    };

    String result = ipAddressSupport.forward("127.0.0.1", PUBLIC_PORT, PROTOCOL, PRIVATE_PORT, VM_ID);
    assertEquals("IpAddressSupport.forward() doesn't return correct result",
            new AzureRuleIdParts(VM_ID, Protocol.TCP.toString(), String.valueOf(PRIVATE_PORT)).toProviderId(),
            result);
    assertEquals("PUT count doesn't match", 1, putCount.get());
}

From source file:com.seleritycorp.common.base.http.client.HttpRequestTest.java

@Test
public void testExecuteAndStreamOk() throws Exception {
    reset(responseFactory);//from  w  w w .java  2s. co m

    StringReader stringReader = new StringReader("response");
    ReaderInputStream readerInputStream = new ReaderInputStream(stringReader);
    expect(responseStreamFactory.create(backendResponse)).andReturn(httpResponseStream);
    expect(httpResponseStream.getBodyAsStream()).andReturn(readerInputStream);

    replayAll();

    HttpRequest request = createHttpRequest("foo");
    HttpResponseStream response = request.executeAndStream();
    String result = IOUtils.toString(response.getBodyAsStream());

    verifyAll();

    assertThat(result).isEqualTo("response");

    HttpUriRequest backendRequest = backendRequestCapture.getValue();
    assertThat(backendRequest.getMethod()).isEqualTo("GET");
    assertThat(backendRequest.getURI().toString()).isEqualTo("foo");
}

From source file:org.dasein.cloud.azure.tests.network.AzureIpAddressSupportTest.java

@Test
public void stopForwardToServerShouldPostCorrectRequest() throws CloudException, InternalException {
    final AtomicInteger putCount = new AtomicInteger(0);
    new MockUp<CloseableHttpClient>() {
        @Mock(invocations = 2)/*  ww  w  . j  a  va 2 s. c  o  m*/
        public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException {
            if (request.getMethod().equals("GET")) {
                DaseinObjectToXmlEntity<PersistentVMRoleModel> daseinEntity = new DaseinObjectToXmlEntity<PersistentVMRoleModel>(
                        createPersistentVMRoleModelWithEndpoint());
                assertGet(request, EXPECTED_URL,
                        new Header[] { new BasicHeader("x-ms-version", "2012-03-01") });
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else if (request.getMethod().equals("PUT")) {
                putCount.incrementAndGet();
                PersistentVMRoleModel persistentVMRoleModel = createPersistentVMRoleModelWithoutEndpoint();
                //set an empty list otherwise unitils will assert fail as one is null while another is empty list
                persistentVMRoleModel.getConfigurationSets().get(0)
                        .setInputEndpoints(new ArrayList<PersistentVMRoleModel.InputEndpoint>());
                assertPut(request, EXPECTED_URL, new Header[] { new BasicHeader("x-ms-version", "2012-03-01") },
                        persistentVMRoleModel);
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_ACCEPTED), null,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else {
                throw new IOException("Request is not mocked");
            }
        }
    };
    String ruleId = new AzureRuleIdParts(VM_ID, Protocol.TCP.toString(), String.valueOf(PRIVATE_PORT))
            .toProviderId();
    ipAddressSupport.stopForwardToServer(ruleId, VM_ID);
    assertEquals("PUT count doesn't match", 1, putCount.get());
}

From source file:com.clarionmedia.infinitum.web.rest.impl.CachingEnabledRestfulClient.java

private RestResponse executeRequest(HashableHttpRequest hashableHttpRequest) {
    if (mIsAuthenticated)
        mAuthStrategy.authenticate(hashableHttpRequest.unwrap());
    if (mResponseCache.containsKey(hashableHttpRequest)) {
        RestResponse cachedResponse = mResponseCache.get(hashableHttpRequest);
        if (cachedResponse != null)
            return cachedResponse;
    }/*  w  w w . j a v a 2s  .  c o  m*/
    HttpUriRequest httpRequest = hashableHttpRequest.unwrap();
    mLogger.debug("Sending " + httpRequest.getMethod() + " request to " + httpRequest.getURI() + " with "
            + httpRequest.getAllHeaders().length + " headers");
    HttpClient httpClient = new DefaultHttpClient(mHttpParams);
    try {
        HttpResponse response = httpClient.execute(httpRequest);
        RestResponse restResponse = new RestResponse(response);
        StatusLine statusLine = response.getStatusLine();
        restResponse.setStatusCode(statusLine.getStatusCode());
        HttpEntity entity = response.getEntity();
        if (entity == null) {
            restResponse.setResponseData(new byte[] {});
        } else {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            entity.writeTo(out);
            out.close();
            restResponse.setResponseData(out.toByteArray());
        }
        long expiration = getResponseExpiration(restResponse);
        if (expiration > 0)
            mResponseCache.put(hashableHttpRequest, restResponse, expiration);
        return restResponse;
    } catch (ClientProtocolException e) {
        mLogger.error("Unable to send " + httpRequest.getMethod() + " request", e);
        return null;
    } catch (IOException e) {
        mLogger.error("Unable to read web service response", e);
        return null;
    }
}

From source file:com.clarionmedia.infinitum.http.rest.impl.CachingEnabledRestfulClient.java

private RestResponse executeRequest(HashableHttpRequest hashableHttpRequest) {
    if (mIsAuthenticated)
        mAuthStrategy.authenticate(hashableHttpRequest);
    if (mResponseCache.containsKey(hashableHttpRequest)) {
        RestResponse cachedResponse = mResponseCache.get(hashableHttpRequest);
        if (cachedResponse != null)
            return cachedResponse;
    }/*  w w w.j  a  v a  2s .  c o  m*/
    HttpUriRequest httpRequest = hashableHttpRequest.unwrap();
    mLogger.debug("Sending " + httpRequest.getMethod() + " request to " + httpRequest.getURI() + " with "
            + httpRequest.getAllHeaders().length + " headers");
    HttpClient httpClient = new DefaultHttpClient(mHttpParams);
    try {
        HttpResponse response = httpClient.execute(httpRequest);
        RestResponse restResponse = new RestResponse(response);
        StatusLine statusLine = response.getStatusLine();
        restResponse.setStatusCode(statusLine.getStatusCode());
        HttpEntity entity = response.getEntity();
        if (entity == null) {
            restResponse.setResponseData(new byte[] {});
        } else {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            entity.writeTo(out);
            out.close();
            restResponse.setResponseData(out.toByteArray());
        }
        long expiration = getResponseExpiration(restResponse);
        if (expiration > 0)
            mResponseCache.put(hashableHttpRequest, restResponse, expiration);
        return restResponse;
    } catch (ClientProtocolException e) {
        mLogger.error("Unable to send " + httpRequest.getMethod() + " request", e);
        return null;
    } catch (IOException e) {
        mLogger.error("Unable to read web service response", e);
        return null;
    }
}