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

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

Introduction

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

Prototype

public abstract String getMethod();

Source Link

Usage

From source file:com.graphaware.test.util.TestHttpClient.java

/**
 * Issue a HTTP call and assert the response status code.
 *
 * @param method             HTTP method.
 * @param expectedStatusCode expected status code.
 * @return the body of the response.//  w ww .j  a  v a  2s  .c o  m
 */
public String method(HttpRequestBase method, final int expectedStatusCode) {
    try {
        String result = client.execute(method, responseHandler(expectedStatusCode));

        LOG.debug("HTTP " + method.getMethod() + " returned: " + result);

        return result;

    } catch (IOException e) {
        fail(e.getMessage());
        return null;
    }
}

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

@Test
public void testSetReadTimeout() throws Exception {
    replayAll();/* w w w .ja va2s  .  co  m*/

    HttpRequest request = createHttpRequest("foo");
    HttpRequest requestAfterSetting = request.setReadTimeoutMillis(4711);
    HttpResponse response = request.execute();

    verifyAll();

    assertThat(request).isSameAs(requestAfterSetting);
    assertThat(response).isEqualTo(httpResponse);

    HttpUriRequest backendRequestRaw = backendRequestCapture.getValue();
    assertThat(backendRequestRaw).isInstanceOf(HttpRequestBase.class);
    HttpRequestBase backendRequest = (HttpRequestBase) backendRequestRaw;
    assertThat(backendRequest.getMethod()).isEqualTo("GET");
    assertThat(backendRequest.getURI().toString()).isEqualTo("foo");
    assertThat(backendRequest.getConfig().getSocketTimeout()).isEqualTo(4711);
}

From source file:com.wareninja.android.commonutils.foursquareV2.http.AbstractHttpApi.java

/**
 * execute() an httpRequest catching exceptions and returning null instead.
 *
 * @param httpRequest/*from  w  ww . j a  v a 2  s .  com*/
 * @return
 * @throws IOException
 */
public HttpResponse executeHttpRequest(HttpRequestBase httpRequest) throws IOException {
    if (DEBUG)
        Log.d(TAG,
                "executing HttpRequest for: " + httpRequest.getURI().toString() + "|" + httpRequest.getMethod()
        //+ "|" + httpRequest.getParams()
        //+ "|" + httpRequest.getAllHeaders()
        );
    /*
    // YG: just for debugging
    String headersStr = "";
    Header[] headers = httpRequest.getAllHeaders();
    for (Header header:headers) {
       headersStr += "|" + header.getName() + ":" + header.getValue();
    }
    String paramsStr = "";
    HttpParams params = httpRequest.getParams();
    paramsStr += "|fs_username=" + params.getParameter("fs_username");
    paramsStr += "|fs_password=" + params.getParameter("fs_password");
    if (DEBUG) Log.d(TAG, "HttpRequest Headers for: "
        + httpRequest.getURI().toString()
        + "|" + headersStr
        + "|" + paramsStr
        );
    */
    /*
    executing HttpRequest for: https://api.foursquare.com/v1/authexchange.json|POST
    HttpRequest Headers for: https://api.foursquare.com/v1/authexchange.json|
    |User-Agent:com.wareninja.android.mayormonster:1|Authorization:OAuth oauth_version="1.0",oauth_nonce="3568494401228",oauth_signature_method="HMAC-SHA1",oauth_consumer_key="P5BV4EIC5RC5MF1STSVPNLPRBF3M5S0OVXKRLIIN0QMU3BEA",oauth_token="",oauth_timestamp="1294862657",oauth_signature="dq7ej2ChkH8uXqLKJ2qICrcIUgk%3D"|
    |fs_username=null|fs_password=null
            
    HttpRequest Headers for: https://api.foursquare.com/v1/authexchange.json||User-Agent:com.wareninja.android.mayormonster:1|Authorization:OAuth oauth_version="1.0",oauth_nonce="3568497175618",oauth_signature_method="HMAC-SHA1",oauth_consumer_key="P5BV4EIC5RC5MF1STSVPNLPRBF3M5S0OVXKRLIIN0QMU3BEA",oauth_token="",oauth_timestamp="1294862657",oauth_signature="5BHzUcaSioV%2BdIX5HiB9C2AyuzA%3D"|
    |fs_username=null|fs_password=null
            
            
     */

    //-WareNinjaUtils.trustEveryone();//YG

    try {
        mHttpClient.getConnectionManager().closeExpiredConnections();
        return mHttpClient.execute(httpRequest);
    } catch (IOException e) {
        httpRequest.abort();
        throw e;
    }
}

From source file:com.ibm.sbt.test.lib.MockService.java

@Override
protected HttpResponse executeRequest(HttpClient httpClient, HttpRequestBase httpRequestBase, Args args)
        throws ClientServicesException {

    switch (this.mode) {
    case REPLAY://from w  w  w .j a va  2 s.co  m
        return serializer.replayResponse();
    case PASSTHROUGH:
        return super.executeRequest(httpClient, httpRequestBase, args);
    case RECORD:
        HttpResponse response;
        response = super.executeRequest(httpClient, httpRequestBase, args);
        System.out.println(httpRequestBase.getMethod() + " " + httpRequestBase.getURI() + ": "
                + response.getStatusLine().getStatusCode());
        return serializer.recordResponse(response);
    default:
        throw new UnsupportedOperationException("Invalid mode " + this.mode);
    }
}

From source file:com.getblimp.api.client.Blimp.java

private String execute(HttpRequestBase request) throws IOException, RuntimeException {
    logger.fine("Entering Blimp.execute");

    CloseableHttpClient client = HttpClients.createDefault();

    logger.finer("Blimp.execute executing HTTP method: " + request.getMethod());
    HttpResponse response = client.execute(request);

    logger.finer("Response status code: " + String.valueOf(response.getStatusLine().getStatusCode()));
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK
            && response.getStatusLine().getStatusCode() != HttpStatus.SC_ACCEPTED) {
        throw new RuntimeException("Request Failed: " + "HTTP Status code: "
                + String.valueOf(response.getStatusLine().getStatusCode()));
    }/*  w  w  w .j  a v a2s  . c  o m*/
    BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    logger.finer("Reading response entity.");
    logger.finer("Output from Server ....");
    String tmpOutput;
    StringBuilder output = new StringBuilder();
    while ((tmpOutput = br.readLine()) != null) {
        output.append(tmpOutput);
    }

    client.close();

    logger.finer("Blimp.execute output: " + output.toString());
    return output.toString();
}

From source file:org.fao.geonet.utils.AbstractHttpRequest.java

protected String getSentData(HttpRequestBase httpMethod) {
    URI uri = httpMethod.getURI();
    StringBuilder sentData = new StringBuilder(httpMethod.getMethod()).append(" ").append(uri.getPath());

    if (uri.getQuery() != null) {
        sentData.append("?" + uri.getQuery());
    }/* w w  w .j ava 2  s. c om*/

    sentData.append("\r\n");

    for (Header h : httpMethod.getAllHeaders()) {
        sentData.append(h);
    }

    sentData.append("\r\n");

    if (httpMethod instanceof HttpPost) {
        sentData.append(postData);
    }

    return sentData.toString();
}

From source file:com.arrow.acs.client.api.ApiAbstract.java

private ApiRequestSigner getSigner(HttpRequestBase request, Instant timestamp) {
    Validate.notNull(request, "request is null");
    Validate.notNull(timestamp, "timestamp is null");
    Validate.notEmpty(apiConfig.getApiKey(), "apiKey is empty");
    Validate.notEmpty(apiConfig.getSecretKey(), "secretKey is empty");
    return ApiRequestSigner.create(apiConfig.getSecretKey()).method(request.getMethod())
            .canonicalUri(request.getURI().getPath()).apiKey(apiConfig.getApiKey())
            .timestamp(timestamp.toString());
}

From source file:com.mgmtp.perfload.core.client.web.http.DefaultHttpClientManager.java

/**
 * Executes an HTTP request using the internal {@link HttpClient} instance encapsulating the
 * Http response in the returns {@link ResponseInfo} object. This method takes to time
 * measurements around the request execution, one after calling
 * {@link HttpClient#execute(org.apache.http.client.methods.HttpUriRequest, HttpContext)} (~
 * first-byte measurment) and the other one later after the complete response was read from the
 * stream. These measurements are return as properties of the {@link ResponseInfo} object.
 *//*from  w w  w .j  ava  2  s.  c om*/
@Override
public ResponseInfo executeRequest(final HttpRequestBase request, final HttpContext context,
        final UUID requestId) throws IOException {
    request.addHeader(EXECUTION_ID_HEADER, executionId.toString());
    request.addHeader(OPERATION_HEADER, operation);
    request.addHeader(REQUEST_ID_HEADER, requestId.toString());

    String uri = request.getURI().toString();
    String type = request.getMethod();

    TimeInterval tiBeforeBody = new TimeInterval();
    TimeInterval tiTotal = new TimeInterval();

    tiBeforeBody.start();
    tiTotal.start();
    long timestamp = System.currentTimeMillis();

    HttpResponse response = getHttpClient().execute(request, context);
    tiBeforeBody.stop();

    // This actually downloads the response body:
    HttpEntity entity = response.getEntity();
    byte[] body = EntityUtils.toByteArray(entity);
    tiTotal.stop();

    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    String statusMsg = statusLine.getReasonPhrase();
    String responseCharset = EntityUtils.getContentCharSet(entity);
    String contentType = EntityUtils.getContentMimeType(entity);
    String bodyAsString = bodyAsString(contentType, responseCharset, body);

    Header[] headers = response.getAllHeaders();
    Map<String, String> responseHeaders = newHashMapWithExpectedSize(headers.length);
    for (Header header : headers) {
        responseHeaders.put(header.getName(), header.getValue());
    }

    return new ResponseInfo(type, uri, statusCode, statusMsg, responseHeaders, body, bodyAsString,
            responseCharset, contentType, timestamp, tiBeforeBody, tiTotal, executionId, requestId);
}

From source file:com.basho.riak.client.http.util.TestClientHelper.java

@Test
public void store_will_use_post_when_no_key_is_provided() throws ClientProtocolException, IOException {
    when(mockHttpClient.execute(any(HttpUriRequest.class))).thenReturn(mockHttpResponse);
    RiakObject objectWithNoKey = new RiakObject(bucket, null);
    impl.store(objectWithNoKey, meta);//from ww  w . ja  v a 2s.  c  om
    ArgumentCaptor<HttpRequestBase> httpRequestBaseCaptor = ArgumentCaptor.forClass(HttpRequestBase.class);
    verify(mockHttpClient).execute(httpRequestBaseCaptor.capture());

    HttpRequestBase requestObject = httpRequestBaseCaptor.getValue();
    assertEquals("Store without key needs to be POST for Riak to understand.", "POST",
            requestObject.getMethod());
}

From source file:com.gsma.mobileconnect.impl.RequestTokenTest.java

@Test
public void requestToken_withDefaults_shouldCreateExpectedRequest()
        throws OIDCException, DiscoveryResponseExpiredException, IOException, RestException {
    // GIVEN/*w  w  w.ja v  a  2  s  .  c  o m*/
    RestClient mockedRestClient = mock(RestClient.class);
    IOIDC ioidc = Factory.getOIDC(mockedRestClient);
    CaptureRequestTokenResponse captureRequestTokenResponse = new CaptureRequestTokenResponse();
    DiscoveryResponse discoveryResponse = new DiscoveryResponse(true, new Date(Long.MAX_VALUE), 0, null,
            parseJson(OPERATOR_JSON_STRING));

    final CaptureHttpRequestBase captureHttpRequestBase = new CaptureHttpRequestBase();
    final RestResponse restResponse = new RestResponse(null, 0, null, "{}");

    doAnswer(new Answer() {
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            Object[] args = invocationOnMock.getArguments();
            HttpRequestBase requestBase = (HttpRequestBase) args[0];
            captureHttpRequestBase.setValue(requestBase);
            return restResponse;
        }
    }).when(mockedRestClient).callRestEndPoint(any(HttpRequestBase.class), any(HttpClientContext.class),
            eq(30000), Matchers.<List<KeyValuePair>>any());

    // WHEN
    ioidc.requestToken(discoveryResponse, "", "", null, captureRequestTokenResponse);

    // THEN
    HttpRequestBase request = captureHttpRequestBase.getValue();

    assertEquals(TOKEN_HREF, request.getURI().toString());
    assertEquals("POST", request.getMethod());
    assertEquals("application/x-www-form-urlencoded", request.getFirstHeader("Content-Type").getValue());
    assertEquals("application/json", request.getFirstHeader("accept").getValue());

    assertTrue(request instanceof HttpPost);

    HttpPost postRequest = (HttpPost) request;
    List<NameValuePair> contents = URLEncodedUtils.parse(postRequest.getEntity());

    assertEquals("", findValueOfName(contents, "code"));
    assertEquals("authorization_code", findValueOfName(contents, "grant_type"));
    assertEquals("", findValueOfName(contents, "redirect_uri"));
}