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.client.Request.java

static Request get(GetRequest getRequest) {
    String endpoint = endpoint(getRequest.index(), getRequest.type(), getRequest.id());

    Params parameters = Params.builder();
    parameters.withPreference(getRequest.preference());
    parameters.withRouting(getRequest.routing());
    parameters.withParent(getRequest.parent());
    parameters.withRefresh(getRequest.refresh());
    parameters.withRealtime(getRequest.realtime());
    parameters.withStoredFields(getRequest.storedFields());
    parameters.withVersion(getRequest.version());
    parameters.withVersionType(getRequest.versionType());
    parameters.withFetchSourceContext(getRequest.fetchSourceContext());

    return new Request(HttpGet.METHOD_NAME, endpoint, parameters.getParams(), null);
}

From source file:com.uploader.Vimeo.java

private VimeoResponse apiRequest(String endpoint, String methodName, Map<String, String> params, File file)
        throws IOException {

    // try(CloseableHttpClient client = HttpClientBuilder.create().build()) {

    CloseableHttpClient client = HttpClientBuilder.create().build();
    // CloseableHttpClient client = HttpClients.createDefault();
    System.out.println("Building HTTP Client");

    // try {/*  ww  w. j  av  a2s .co  m*/
    //     client = 
    // }   catch(Exception e) {
    //     System.out.println("Err in CloseableHttpClient");
    // }

    // System.out.println(client);

    HttpRequestBase request = null;
    String url = null;
    if (endpoint.startsWith("http")) {
        url = endpoint;
    } else {
        url = new StringBuffer(VIMEO_SERVER).append(endpoint).toString();
    }
    System.out.println(url);
    if (methodName.equals(HttpGet.METHOD_NAME)) {
        request = new HttpGet(url);
    } else if (methodName.equals(HttpPost.METHOD_NAME)) {
        request = new HttpPost(url);
    } else if (methodName.equals(HttpPut.METHOD_NAME)) {
        request = new HttpPut(url);
    } else if (methodName.equals(HttpDelete.METHOD_NAME)) {
        request = new HttpDelete(url);
    } else if (methodName.equals(HttpPatch.METHOD_NAME)) {
        request = new HttpPatch(url);
    }

    request.addHeader("Accept", "application/vnd.vimeo.*+json; version=3.2");
    request.addHeader("Authorization", new StringBuffer(tokenType).append(" ").append(token).toString());

    HttpEntity entity = null;
    if (params != null) {
        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        for (String key : params.keySet()) {
            postParameters.add(new BasicNameValuePair(key, params.get(key)));
        }
        entity = new UrlEncodedFormEntity(postParameters);
    } else {
        if (file != null) {
            entity = new FileEntity(file, ContentType.MULTIPART_FORM_DATA);
        }
    }
    if (entity != null) {
        if (request instanceof HttpPost) {
            ((HttpPost) request).setEntity(entity);
        } else if (request instanceof HttpPatch) {
            ((HttpPatch) request).setEntity(entity);
        } else if (request instanceof HttpPut) {
            ((HttpPut) request).setEntity(entity);
        }
    }
    CloseableHttpResponse response = client.execute(request);
    String responseAsString = null;
    int statusCode = response.getStatusLine().getStatusCode();
    if (methodName.equals(HttpPut.METHOD_NAME) || methodName.equals(HttpDelete.METHOD_NAME)) {
        JSONObject out = new JSONObject();
        for (Header header : response.getAllHeaders()) {
            try {
                out.put(header.getName(), header.getValue());
            } catch (Exception e) {
                System.out.println("Err in out.put");
            }
        }
        responseAsString = out.toString();
    } else if (statusCode != 204) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        responseAsString = out.toString("UTF-8");
        out.close();
    }
    JSONObject json = null;
    try {
        json = new JSONObject(responseAsString);
    } catch (Exception e) {
        json = new JSONObject();
    }
    VimeoResponse vimeoResponse = new VimeoResponse(json, statusCode);
    response.close();
    client.close();

    return vimeoResponse;

    // }   catch(IOException e)  {
    //     System.out.println("Error Building HTTP Client");
    // }
}

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

public void testInfo() {
    Request request = RequestConverters.info();
    assertEquals("/", request.getEndpoint());
    assertEquals(0, request.getParameters().size());
    assertNull(request.getEntity());//from  w  w  w  . ja  va 2  s .co m
    assertEquals(HttpGet.METHOD_NAME, request.getMethod());
}

From source file:org.cloudifysource.restclient.RestClientExecutor.java

private <T> T executeRequest(final HttpRequestBase request,
        final TypeReference<Response<T>> responseTypeReference) throws RestClientException {
    HttpResponse httpResponse = null;//from w  w  w  . j a  v a2 s  .  c  om
    try {
        IOException lastException = null;
        int numOfTrials = DEFAULT_TRIALS_NUM;
        if (HttpGet.METHOD_NAME.equals(request.getMethod())) {
            numOfTrials = GET_TRIALS_NUM;
        }
        for (int i = 0; i < numOfTrials; i++) {
            try {
                httpResponse = httpClient.execute(request);
                lastException = null;
                break;
            } catch (IOException e) {
                if (logger.isLoggable(Level.FINER)) {
                    logger.finer("Execute get request to " + request.getURI() + ". try number " + (i + 1)
                            + " out of " + GET_TRIALS_NUM + ", error is " + e.getMessage());
                }
                lastException = e;
            }
        }
        if (lastException != null) {
            if (logger.isLoggable(Level.WARNING)) {
                logger.warning("Failed executing " + request.getMethod() + " request to " + request.getURI()
                        + " : " + lastException.getMessage());
            }
            throw MessagesUtils.createRestClientIOException(RestClientMessageKeys.EXECUTION_FAILURE.getName(),
                    lastException, request.getURI());
        }
        String url = request.getURI().toString();
        checkForError(httpResponse, url);
        return getResponseObject(responseTypeReference, httpResponse, url);
    } finally {
        request.abort();
    }
}

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

public void testGet() {
    getAndExistsTest(RequestConverters::get, HttpGet.METHOD_NAME);
}

From source file:alien4cloud.paas.cloudify2.rest.external.RestClientExecutor.java

private <T> T executeRequest(final HttpRequestBase request,
        final TypeReference<Response<T>> responseTypeReference) throws RestClientException {
    HttpResponse httpResponse = null;/*from  ww w. ja va2 s .  co m*/
    IOException lastException = null;
    int numOfTrials = DEFAULT_TRIALS_NUM;
    if (HttpGet.METHOD_NAME.equals(request.getMethod())) {
        numOfTrials = GET_TRIALS_NUM;
    }
    for (int i = 0; i < numOfTrials; i++) {
        try {
            httpResponse = httpClient.execute(request);
            lastException = null;
            break;
        } catch (IOException e) {
            if (logger.isLoggable(Level.FINER)) {
                logger.finer("Execute get request to " + request.getURI() + ". try number " + (i + 1)
                        + " out of " + GET_TRIALS_NUM + ", error is " + e.getMessage());
            }
            lastException = e;
        }
    }
    if (lastException != null) {
        if (logger.isLoggable(Level.WARNING)) {
            logger.warning("Failed executing " + request.getMethod() + " request to " + request.getURI() + " : "
                    + lastException.getMessage());
        }
        throw MessagesUtils.createRestClientIOException(RestClientMessageKeys.EXECUTION_FAILURE.getName(),
                lastException, request.getURI());
    }
    String url = request.getURI().toString();
    checkForError(httpResponse, url);
    return getResponseObject(responseTypeReference, httpResponse, url);
}

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

/**
 * Get a file from the content server, returning the raw Apache HTTP Components response object
 * so you can stream it or work with it how you need.
 * You *must* call .getEntity().consumeContent() on the returned HttpResponse object or you might leak
 * connections.//from  w  ww.  j av  a  2s  . c o  m
 *
 * @param path
 * @param etag Version of the file
 * @return
 * @throws IOException
 */
protected HttpResponse getFile(String path, String etag) throws IOException {
    HttpUriRequest req = this.buildRequest(HttpGet.METHOD_NAME, "/files/" + ROOT + path, true);
    if (StringUtils.isNotBlank(etag)) {
        req.addHeader("If-None-Match", etag);
    }
    return this.request(req);
}

From source file:org.elasticsearch.repositories.s3.AmazonS3Fixture.java

/** Builds the default request handlers **/
private PathTrie<RequestHandler> defaultHandlers(final Map<String, Bucket> buckets, final Bucket ec2Bucket,
        final Bucket ecsBucket) {
    final PathTrie<RequestHandler> handlers = new PathTrie<>(RestUtils.REST_DECODER);

    // HEAD Object
    ////w  w w .j av a  2 s .  c om
    // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectHEAD.html
    objectsPaths(authPath(HttpHead.METHOD_NAME, "/{bucket}"))
            .forEach(path -> handlers.insert(path, (request) -> {
                final String bucketName = request.getParam("bucket");

                final Bucket bucket = buckets.get(bucketName);
                if (bucket == null) {
                    return newBucketNotFoundError(request.getId(), bucketName);
                }

                final String objectName = objectName(request.getParameters());
                for (Map.Entry<String, byte[]> object : bucket.objects.entrySet()) {
                    if (object.getKey().equals(objectName)) {
                        return new Response(RestStatus.OK.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE);
                    }
                }
                return newObjectNotFoundError(request.getId(), objectName);
            }));

    // PUT Object
    //
    // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html
    objectsPaths(authPath(HttpPut.METHOD_NAME, "/{bucket}"))
            .forEach(path -> handlers.insert(path, (request) -> {
                final String destBucketName = request.getParam("bucket");

                final Bucket destBucket = buckets.get(destBucketName);
                if (destBucket == null) {
                    return newBucketNotFoundError(request.getId(), destBucketName);
                }

                final String destObjectName = objectName(request.getParameters());

                // This is a chunked upload request. We should have the header "Content-Encoding : aws-chunked,gzip"
                // to detect it but it seems that the AWS SDK does not follow the S3 guidelines here.
                //
                // See https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-streaming.html
                //
                String headerDecodedContentLength = request.getHeader("X-amz-decoded-content-length");
                if (headerDecodedContentLength != null) {
                    int contentLength = Integer.valueOf(headerDecodedContentLength);

                    // Chunked requests have a payload like this:
                    //
                    // 105;chunk-signature=01d0de6be013115a7f4794db8c4b9414e6ec71262cc33ae562a71f2eaed1efe8
                    // ...  bytes of data ....
                    // 0;chunk-signature=f890420b1974c5469aaf2112e9e6f2e0334929fd45909e03c0eff7a84124f6a4
                    //
                    try (BufferedInputStream inputStream = new BufferedInputStream(
                            new ByteArrayInputStream(request.getBody()))) {
                        int b;
                        // Moves to the end of the first signature line
                        while ((b = inputStream.read()) != -1) {
                            if (b == '\n') {
                                break;
                            }
                        }

                        final byte[] bytes = new byte[contentLength];
                        inputStream.read(bytes, 0, contentLength);

                        destBucket.objects.put(destObjectName, bytes);
                        return new Response(RestStatus.OK.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE);
                    }
                }

                return newInternalError(request.getId(), "Something is wrong with this PUT request");
            }));

    // DELETE Object
    //
    // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectDELETE.html
    objectsPaths(authPath(HttpDelete.METHOD_NAME, "/{bucket}"))
            .forEach(path -> handlers.insert(path, (request) -> {
                final String bucketName = request.getParam("bucket");

                final Bucket bucket = buckets.get(bucketName);
                if (bucket == null) {
                    return newBucketNotFoundError(request.getId(), bucketName);
                }

                final String objectName = objectName(request.getParameters());
                bucket.objects.remove(objectName);
                return new Response(RestStatus.NO_CONTENT.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE);
            }));

    // GET Object
    //
    // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html
    objectsPaths(authPath(HttpGet.METHOD_NAME, "/{bucket}"))
            .forEach(path -> handlers.insert(path, (request) -> {
                final String bucketName = request.getParam("bucket");

                final Bucket bucket = buckets.get(bucketName);
                if (bucket == null) {
                    return newBucketNotFoundError(request.getId(), bucketName);
                }

                final String objectName = objectName(request.getParameters());
                if (bucket.objects.containsKey(objectName)) {
                    return new Response(RestStatus.OK.getStatus(), contentType("application/octet-stream"),
                            bucket.objects.get(objectName));

                }
                return newObjectNotFoundError(request.getId(), objectName);
            }));

    // HEAD Bucket
    //
    // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketHEAD.html
    handlers.insert(authPath(HttpHead.METHOD_NAME, "/{bucket}"), (request) -> {
        String bucket = request.getParam("bucket");
        if (Strings.hasText(bucket) && buckets.containsKey(bucket)) {
            return new Response(RestStatus.OK.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE);
        } else {
            return newBucketNotFoundError(request.getId(), bucket);
        }
    });

    // GET Bucket (List Objects) Version 1
    //
    // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html
    handlers.insert(authPath(HttpGet.METHOD_NAME, "/{bucket}/"), (request) -> {
        final String bucketName = request.getParam("bucket");

        final Bucket bucket = buckets.get(bucketName);
        if (bucket == null) {
            return newBucketNotFoundError(request.getId(), bucketName);
        }

        String prefix = request.getParam("prefix");
        if (prefix == null) {
            prefix = request.getHeader("Prefix");
        }
        return newListBucketResultResponse(request.getId(), bucket, prefix);
    });

    // Delete Multiple Objects
    //
    // https://docs.aws.amazon.com/AmazonS3/latest/API/multiobjectdeleteapi.html
    handlers.insert(nonAuthPath(HttpPost.METHOD_NAME, "/"), (request) -> {
        final List<String> deletes = new ArrayList<>();
        final List<String> errors = new ArrayList<>();

        if (request.getParam("delete") != null) {
            // The request body is something like:
            // <Delete><Object><Key>...</Key></Object><Object><Key>...</Key></Object></Delete>
            String requestBody = Streams
                    .copyToString(new InputStreamReader(new ByteArrayInputStream(request.getBody()), UTF_8));
            if (requestBody.startsWith("<Delete>")) {
                final String startMarker = "<Key>";
                final String endMarker = "</Key>";

                int offset = 0;
                while (offset != -1) {
                    offset = requestBody.indexOf(startMarker, offset);
                    if (offset > 0) {
                        int closingOffset = requestBody.indexOf(endMarker, offset);
                        if (closingOffset != -1) {
                            offset = offset + startMarker.length();
                            final String objectName = requestBody.substring(offset, closingOffset);

                            boolean found = false;
                            for (Bucket bucket : buckets.values()) {
                                if (bucket.objects.containsKey(objectName)) {
                                    final Response authResponse = authenticateBucket(request, bucket);
                                    if (authResponse != null) {
                                        return authResponse;
                                    }
                                    bucket.objects.remove(objectName);
                                    found = true;
                                }
                            }

                            if (found) {
                                deletes.add(objectName);
                            } else {
                                errors.add(objectName);
                            }
                        }
                    }
                }
                return newDeleteResultResponse(request.getId(), deletes, errors);
            }
        }
        return newInternalError(request.getId(), "Something is wrong with this POST multiple deletes request");
    });

    // non-authorized requests

    TriFunction<String, String, String, Response> credentialResponseFunction = (profileName, key, token) -> {
        final Date expiration = new Date(new Date().getTime() + TimeUnit.DAYS.toMillis(1));
        final String response = "{" + "\"AccessKeyId\": \"" + key + "\"," + "\"Expiration\": \""
                + DateUtils.formatISO8601Date(expiration) + "\"," + "\"RoleArn\": \""
                + randomAsciiAlphanumOfLengthBetween(random, 1, 20) + "\"," + "\"SecretAccessKey\": \""
                + randomAsciiAlphanumOfLengthBetween(random, 1, 20) + "\"," + "\"Token\": \"" + token + "\""
                + "}";

        final Map<String, String> headers = new HashMap<>(contentType("application/json"));
        return new Response(RestStatus.OK.getStatus(), headers, response.getBytes(UTF_8));
    };

    // GET
    //
    // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
    handlers.insert(nonAuthPath(HttpGet.METHOD_NAME, "/latest/meta-data/iam/security-credentials/"),
            (request) -> {
                final String response = EC2_PROFILE;

                final Map<String, String> headers = new HashMap<>(contentType("text/plain"));
                return new Response(RestStatus.OK.getStatus(), headers, response.getBytes(UTF_8));
            });

    // GET
    //
    // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
    handlers.insert(
            nonAuthPath(HttpGet.METHOD_NAME, "/latest/meta-data/iam/security-credentials/{profileName}"),
            (request) -> {
                final String profileName = request.getParam("profileName");
                if (EC2_PROFILE.equals(profileName) == false) {
                    return new Response(RestStatus.NOT_FOUND.getStatus(), new HashMap<>(),
                            "unknown profile".getBytes(UTF_8));
                }
                return credentialResponseFunction.apply(profileName, ec2Bucket.key, ec2Bucket.token);
            });

    // GET
    //
    // https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html
    handlers.insert(nonAuthPath(HttpGet.METHOD_NAME, "/ecs_credentials_endpoint"),
            (request) -> credentialResponseFunction.apply("CPV_ECS", ecsBucket.key, ecsBucket.token));

    return handlers;
}

From source file:io.cloudslang.content.xml.utils.XmlUtils.java

public static String createXmlDocumentFromUrl(CommonInputs commonInputs)
        throws ParserConfigurationException, SAXException, IOException {
    CSHttpClient scoreHttpClient = new CSHttpClient();
    HttpClientInputs httpClientInputs = new HttpClientInputs();
    httpClientInputs.setMethod(HttpGet.METHOD_NAME);
    httpClientInputs.setUrl(commonInputs.getXmlDocument());

    if (commonInputs.getUsername().isEmpty()) {
        httpClientInputs.setAuthType(AuthTypes.ANONYMOUS);
    } else {/*from   w w  w.  ja  v  a 2 s .  c  om*/
        httpClientInputs.setAuthType(AuthTypes.BASIC);
        httpClientInputs.setUsername(commonInputs.getUsername());
        httpClientInputs.setPassword(commonInputs.getPassword());
    }
    httpClientInputs.setRequestCharacterSet(StandardCharsets.UTF_8.toString());
    httpClientInputs.setResponseCharacterSet(StandardCharsets.UTF_8.toString());
    httpClientInputs.setTrustAllRoots(commonInputs.getTrustAllRoots());
    httpClientInputs.setKeystore(commonInputs.getKeystore());
    httpClientInputs.setKeystorePassword(commonInputs.getKeystorePassword());
    httpClientInputs.setTrustKeystore(commonInputs.getTrustKeystore());
    httpClientInputs.setTrustPassword(commonInputs.getTrustPassword());
    httpClientInputs.setX509HostnameVerifier(commonInputs.getX509Hostnameverifier());
    httpClientInputs.setProxyHost(commonInputs.getProxyHost());
    httpClientInputs.setProxyPort(commonInputs.getProxyPort());
    httpClientInputs.setProxyUsername(commonInputs.getProxyUsername());
    httpClientInputs.setProxyPassword(commonInputs.getProxyPassword());

    Map<String, String> requestResponse = scoreHttpClient.execute(httpClientInputs);
    if (!OK_STATUS_CODE.equals(requestResponse.get(CSHttpClient.STATUS_CODE))) {
        throw new RuntimeException("Http request to specified URL: " + commonInputs.getXmlDocument()
                + " failed with status code: " + requestResponse.get(CSHttpClient.STATUS_CODE)
                + ". Request response is: " + requestResponse.get(Constants.Outputs.RETURN_RESULT));
    }
    return requestResponse.get(Constants.Outputs.RETURN_RESULT);
}

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

static Request info() {
    return new Request(HttpGet.METHOD_NAME, "/");
}