Example usage for org.apache.http.client.methods HttpGet METHOD_NAME

List of usage examples for org.apache.http.client.methods HttpGet METHOD_NAME

Introduction

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

Prototype

String METHOD_NAME

To view the source code for org.apache.http.client.methods HttpGet METHOD_NAME.

Click Source Link

Usage

From source file:org.elasticsearch.test.rest.yaml.ClientYamlTestClient.java

/**
 * Calls an api with the provided parameters and body
 *//*from ww w .j ava  2s. c  o m*/
public ClientYamlTestResponse callApi(String apiName, Map<String, String> params, HttpEntity entity,
        Map<String, String> headers) throws IOException {

    if ("raw".equals(apiName)) {
        // Raw requests are bit simpler....
        Map<String, String> queryStringParams = new HashMap<>(params);
        String method = Objects.requireNonNull(queryStringParams.remove("method"),
                "Method must be set to use raw request");
        String path = "/" + Objects.requireNonNull(queryStringParams.remove("path"),
                "Path must be set to use raw request");
        // And everything else is a url parameter!
        try {
            Response response = restClient.performRequest(method, path, queryStringParams, entity);
            return new ClientYamlTestResponse(response);
        } catch (ResponseException e) {
            throw new ClientYamlTestResponseException(e);
        }
    }

    ClientYamlSuiteRestApi restApi = restApi(apiName);

    //divide params between ones that go within query string and ones that go within path
    Map<String, String> pathParts = new HashMap<>();
    Map<String, String> queryStringParams = new HashMap<>();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        if (restApi.getPathParts().contains(entry.getKey())) {
            pathParts.put(entry.getKey(), entry.getValue());
        } else {
            if (restApi.getParams().contains(entry.getKey()) || restSpec.isGlobalParameter(entry.getKey())
                    || restSpec.isClientParameter(entry.getKey())) {
                queryStringParams.put(entry.getKey(), entry.getValue());
            } else {
                throw new IllegalArgumentException(
                        "param [" + entry.getKey() + "] not supported in [" + restApi.getName() + "] " + "api");
            }
        }
    }

    List<String> supportedMethods = restApi.getSupportedMethods(pathParts.keySet());
    String requestMethod;
    if (entity != null) {
        if (!restApi.isBodySupported()) {
            throw new IllegalArgumentException("body is not supported by [" + restApi.getName() + "] api");
        }
        String contentType = entity.getContentType().getValue();
        //randomly test the GET with source param instead of GET/POST with body
        if (sendBodyAsSourceParam(supportedMethods, contentType)) {
            logger.debug("sending the request body as source param with GET method");
            queryStringParams.put("source", EntityUtils.toString(entity));
            queryStringParams.put("source_content_type", contentType);
            requestMethod = HttpGet.METHOD_NAME;
            entity = null;
        } else {
            requestMethod = RandomizedTest.randomFrom(supportedMethods);
        }
    } else {
        if (restApi.isBodyRequired()) {
            throw new IllegalArgumentException("body is required by [" + restApi.getName() + "] api");
        }
        requestMethod = RandomizedTest.randomFrom(supportedMethods);
    }

    //the rest path to use is randomized out of the matching ones (if more than one)
    ClientYamlSuiteRestPath restPath = RandomizedTest.randomFrom(restApi.getFinalPaths(pathParts));
    //Encode rules for path and query string parameters are different. We use URI to encode the path.
    //We need to encode each path part separately, as each one might contain slashes that need to be escaped, which needs to
    //be done manually.
    String requestPath;
    if (restPath.getPathParts().length == 0) {
        requestPath = "/";
    } else {
        StringBuilder finalPath = new StringBuilder();
        for (String pathPart : restPath.getPathParts()) {
            try {
                finalPath.append('/');
                // We append "/" to the path part to handle parts that start with - or other invalid characters
                URI uri = new URI(null, null, null, -1, "/" + pathPart, null, null);
                //manually escape any slash that each part may contain
                finalPath.append(uri.getRawPath().substring(1).replaceAll("/", "%2F"));
            } catch (URISyntaxException e) {
                throw new RuntimeException("unable to build uri", e);
            }
        }
        requestPath = finalPath.toString();
    }

    Header[] requestHeaders = new Header[headers.size()];
    int index = 0;
    for (Map.Entry<String, String> header : headers.entrySet()) {
        logger.info("Adding header {}\n with value {}", header.getKey(), header.getValue());
        requestHeaders[index++] = new BasicHeader(header.getKey(), header.getValue());
    }

    logger.debug("calling api [{}]", apiName);
    try {
        Response response = restClient.performRequest(requestMethod, requestPath, queryStringParams, entity,
                requestHeaders);
        return new ClientYamlTestResponse(response);
    } catch (ResponseException e) {
        throw new ClientYamlTestResponseException(e);
    }
}

From source file:com.microsoft.windowsazure.mobileservices.http.MobileServiceHttpClient.java

/**
 * Makes a request over HTTP//from  w ww.j a v a  2 s.  c om
 *
 * @param path           The path of the request URI
 * @param content        The byte array to send as the request body
 * @param httpMethod     The HTTP Method used to invoke the API
 * @param requestHeaders The extra headers to send in the request
 * @param parameters     The query string parameters sent in the request
 * @param features       The features used in the request
 */
public ListenableFuture<ServiceFilterResponse> request(String path, byte[] content, String httpMethod,
        List<Pair<String, String>> requestHeaders, List<Pair<String, String>> parameters,
        EnumSet<MobileServiceFeatures> features) {
    final SettableFuture<ServiceFilterResponse> future = SettableFuture.create();

    if (path == null || path.trim().equals("")) {
        future.setException(new IllegalArgumentException("request path cannot be null"));
        return future;
    }

    if (httpMethod == null || httpMethod.trim().equals("")) {
        future.setException(new IllegalArgumentException("httpMethod cannot be null"));
        return future;
    }

    Uri.Builder uriBuilder = Uri.parse(mClient.getAppUrl().toString()).buildUpon();
    uriBuilder.path(path);

    if (parameters != null && parameters.size() > 0) {
        for (Pair<String, String> parameter : parameters) {
            uriBuilder.appendQueryParameter(parameter.first, parameter.second);
        }
    }

    ServiceFilterRequestImpl request;
    String url = uriBuilder.build().toString();

    if (httpMethod.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
        request = new ServiceFilterRequestImpl(new HttpGet(url), mClient.getAndroidHttpClientFactory());
    } else if (httpMethod.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
        request = new ServiceFilterRequestImpl(new HttpPost(url), mClient.getAndroidHttpClientFactory());
    } else if (httpMethod.equalsIgnoreCase(HttpPut.METHOD_NAME)) {
        request = new ServiceFilterRequestImpl(new HttpPut(url), mClient.getAndroidHttpClientFactory());
    } else if (httpMethod.equalsIgnoreCase(HttpPatch.METHOD_NAME)) {
        request = new ServiceFilterRequestImpl(new HttpPatch(url), mClient.getAndroidHttpClientFactory());
    } else if (httpMethod.equalsIgnoreCase(HttpDelete.METHOD_NAME)) {
        request = new ServiceFilterRequestImpl(new HttpDelete(url), mClient.getAndroidHttpClientFactory());
    } else {
        future.setException(new IllegalArgumentException("httpMethod not supported"));
        return future;
    }

    String featuresHeader = MobileServiceFeatures.featuresToString(features);
    if (featuresHeader != null) {
        if (requestHeaders == null) {
            requestHeaders = new ArrayList<Pair<String, String>>();
        }

        boolean containsFeatures = false;
        for (Pair<String, String> header : requestHeaders) {
            if (header.first.equals(X_ZUMO_FEATURES)) {
                containsFeatures = true;
                break;
            }
        }

        if (!containsFeatures) {
            // Clone header list to prevent changing user's list
            requestHeaders = new ArrayList<Pair<String, String>>(requestHeaders);
            requestHeaders.add(new Pair<String, String>(X_ZUMO_FEATURES, featuresHeader));
        }
    }

    if (requestHeaders != null && requestHeaders.size() > 0) {
        for (Pair<String, String> header : requestHeaders) {
            request.addHeader(header.first, header.second);
        }
    }

    if (content != null) {
        try {
            request.setContent(content);
        } catch (Exception e) {
            future.setException(e);
            return future;
        }
    }

    MobileServiceConnection conn = mClient.createConnection();

    new RequestAsyncTask(request, conn) {
        @Override
        protected void onPostExecute(ServiceFilterResponse response) {
            if (mTaskException != null) {
                future.setException(mTaskException);
            } else {
                future.set(response);
            }
        }
    }.executeTask();

    return future;
}

From source file:com.uploader.Vimeo.java

public VimeoResponse likesVideo(String videoId) throws IOException {
    return apiRequest(new StringBuffer("/me/likes/").append(videoId).toString(), HttpGet.METHOD_NAME, null,
            null);//from w  ww  .  j  a  v a2  s.com
}

From source file:ch.cyberduck.core.dropbox.client.DropboxClient.java

/**
 * @param path/*w  w  w.j  a  v  a 2  s .  c  om*/
 * @return
 * @throws IOException
 * @throws OAuthException
 */
public ListEntryResponse metadata(String path) throws IOException {
    String[] params = { "list", String.valueOf(false) };
    HttpResponse response = request(this.buildRequest(HttpGet.METHOD_NAME, "/metadata/" + ROOT + path, params));
    return new ListEntryResponse(this.parse(response));
}

From source file:com.seleritycorp.common.base.http.server.HttpRequest.java

/**
 * Checks if a request is a GET request.
 * /*  ww w.  j av a2s.  co m*/
 * @return true, if it is a GET request. false otherwise.
 */
public boolean isMethodGet() {
    return HttpGet.METHOD_NAME.equals(httpServletRequest.getMethod());
}

From source file:org.apache.edgent.test.connectors.http.HttpTest.java

/**
 * Test basic authentication, first with valid user/password
 * and then with invalid (results in 401).
 * @throws Exception//from   w w w  .j a  va 2s .c o m
 */
@Test
public void testBasicAuthentication() throws Exception {

    DirectProvider ep = new DirectProvider();

    Topology topology = ep.newTopology();

    String url = "http://httpbin.org/basic-auth/";

    TStream<Integer> rc = HttpStreams.<String, Integer>requests(topology.strings("A", "B"),
            () -> HttpClients.basic("usA", "pwdA4"), t -> HttpGet.METHOD_NAME,
            t -> url + "us" + t + "/pwd" + t + "4", (t, resp) -> resp.getStatusLine().getStatusCode());

    Tester tester = topology.getTester();

    Condition<List<Integer>> endCondition = tester.streamContents(rc, 200, 401);

    tester.complete(ep, new JsonObject(), endCondition, 10, TimeUnit.SECONDS);

    assertTrue(endCondition.getResult().toString(), endCondition.valid());
}

From source file:ch.cyberduck.core.dropbox.client.DropboxClient.java

/**
 * The account/info API call to Dropbox for getting info about an account attached to the access token.
 *
 * @return/*w  ww .  ja va  2s. com*/
 * @throws IOException
 * @throws OAuthException
 */
public Account account() throws IOException {
    HttpResponse response = request(this.buildRequest(HttpGet.METHOD_NAME, "/account/info"));
    return new Account(this.parse(response));
}

From source file:com.uploader.Vimeo.java

public VimeoResponse checkEmbedPreset(String videoEndPoint, String presetId) throws IOException {
    return apiRequest(new StringBuffer(videoEndPoint).append("/presets/").append(presetId).toString(),
            HttpGet.METHOD_NAME, null, null);
}

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

/**
 * Mocks the synchronous request execution like if it was executed by Elasticsearch.
 */// w  w w  .ja  v  a  2 s. c o m
private Response mockPerformRequest(Request request) throws IOException {
    assertThat(request.getOptions().getHeaders(), hasSize(1));
    Header httpHeader = request.getOptions().getHeaders().get(0);
    final Response mockResponse = mock(Response.class);
    when(mockResponse.getHost()).thenReturn(new HttpHost("localhost", 9200));

    ProtocolVersion protocol = new ProtocolVersion("HTTP", 1, 1);
    when(mockResponse.getStatusLine()).thenReturn(new BasicStatusLine(protocol, 200, "OK"));

    MainResponse response = new MainResponse(httpHeader.getValue(), Version.CURRENT, ClusterName.DEFAULT, "_na",
            Build.CURRENT);
    BytesRef bytesRef = XContentHelper.toXContent(response, XContentType.JSON, false).toBytesRef();
    when(mockResponse.getEntity())
            .thenReturn(new ByteArrayEntity(bytesRef.bytes, ContentType.APPLICATION_JSON));

    RequestLine requestLine = new BasicRequestLine(HttpGet.METHOD_NAME, ENDPOINT, protocol);
    when(mockResponse.getRequestLine()).thenReturn(requestLine);

    return mockResponse;
}