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

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

Introduction

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

Prototype

String METHOD_NAME

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

Click Source Link

Usage

From source file:com.clickntap.vimeo.Vimeo.java

private VimeoResponse apiRequest(String endpoint, String methodName, Map<String, String> params, File file)
        throws IOException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpRequestBase request = null;//from ww w  .  j a  v a  2 s. co  m
    String url = null;
    if (endpoint.startsWith("http")) {
        url = endpoint;
    } else {
        url = new StringBuffer(VIMEO_SERVER).append(endpoint).toString();
    }
    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()) {
            out.put(header.getName(), header.getValue());
        }
        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;
}

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

static Request index(IndexRequest indexRequest) {
    String method = Strings.hasLength(indexRequest.id()) ? HttpPut.METHOD_NAME : HttpPost.METHOD_NAME;

    boolean isCreate = (indexRequest.opType() == DocWriteRequest.OpType.CREATE);
    String endpoint = endpoint(indexRequest.index(), indexRequest.type(), indexRequest.id(),
            isCreate ? "_create" : null);

    Params parameters = Params.builder();
    parameters.withRouting(indexRequest.routing());
    parameters.withParent(indexRequest.parent());
    parameters.withTimeout(indexRequest.timeout());
    parameters.withVersion(indexRequest.version());
    parameters.withVersionType(indexRequest.versionType());
    parameters.withPipeline(indexRequest.getPipeline());
    parameters.withRefreshPolicy(indexRequest.getRefreshPolicy());
    parameters.withWaitForActiveShards(indexRequest.waitForActiveShards());

    BytesRef source = indexRequest.source().toBytesRef();
    ContentType contentType = ContentType.create(indexRequest.getContentType().mediaType());
    HttpEntity entity = new ByteArrayEntity(source.bytes, source.offset, source.length, contentType);

    return new Request(method, endpoint, parameters.getParams(), entity);
}

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

static Request refresh(RefreshRequest refreshRequest) {
    String[] indices = refreshRequest.indices() == null ? Strings.EMPTY_ARRAY : refreshRequest.indices();
    Request request = new Request(HttpPost.METHOD_NAME, endpoint(indices, "_refresh"));

    Params parameters = new Params(request);
    parameters.withIndicesOptions(refreshRequest.indicesOptions());
    return request;
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.CustomApiClientTests.java

@SuppressWarnings("deprecation")
public void testInvokeTypedSingleObjectCallback() throws Throwable {
    final CountDownLatch latch = new CountDownLatch(1);

    // Container to store callback's results and do the asserts.
    final ResultsContainer container = new ResultsContainer();

    final PersonTestObject p = new PersonTestObject("john", "doe", 30);

    MobileServiceClient client = null;//  w  ww  . j  ava2  s. c o m
    try {
        client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    client = client.withFilter(new EchoFilter());

    client.invokeApi("myApi", p, HttpPost.METHOD_NAME, null, PersonTestObject.class,
            new ApiOperationCallback<PersonTestObject>() {

                @Override
                public void onCompleted(PersonTestObject result, Exception exception,
                        ServiceFilterResponse response) {
                    if (exception != null) {
                        container.setException(exception);
                    } else if (result == null) {
                        container.setException(new Exception("Expected one person result"));
                    } else {
                        container.setPerson(result);
                    }

                    latch.countDown();
                }
            });

    latch.await();

    // Asserts
    Exception exception = container.getException();
    if (exception != null) {
        fail(exception.getMessage());
    } else {
        assertEquals(p.getFirstName(), container.getPerson().getFirstName());
        assertEquals(p.getLastName(), container.getPerson().getLastName());
        assertEquals(p.getAge(), container.getPerson().getAge());
    }
}

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 {//w  ww . jav  a  2  s . 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.RequestConverters.java

static Request flush(FlushRequest flushRequest) {
    String[] indices = flushRequest.indices() == null ? Strings.EMPTY_ARRAY : flushRequest.indices();
    Request request = new Request(HttpPost.METHOD_NAME, endpoint(indices, "_flush"));

    Params parameters = new Params(request);
    parameters.withIndicesOptions(flushRequest.indicesOptions());
    parameters.putParam("wait_if_ongoing", Boolean.toString(flushRequest.waitIfOngoing()));
    parameters.putParam("force", Boolean.toString(flushRequest.force()));
    return request;
}

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

static Request flushSynced(SyncedFlushRequest syncedFlushRequest) {
    String[] indices = syncedFlushRequest.indices() == null ? Strings.EMPTY_ARRAY
            : syncedFlushRequest.indices();
    Request request = new Request(HttpPost.METHOD_NAME, endpoint(indices, "_flush/synced"));
    Params parameters = new Params(request);
    parameters.withIndicesOptions(syncedFlushRequest.indicesOptions());
    return request;
}

From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java

public void collect() {
    if (isPingCompat.get()) {
        // back compat w/ old url.availability templates
        super.collect();
        return;/* w w  w . j  a  v a 2  s. c om*/
    }
    this.matches.clear();
    HttpConfig config = new HttpConfig(getTimeoutMillis(), getTimeoutMillis(), proxyHost.get(),
            proxyPort.get());
    AgentKeystoreConfig keystoreConfig = new AgentKeystoreConfig();
    log.debug("isAcceptUnverifiedCert:" + keystoreConfig.isAcceptUnverifiedCert());
    HQHttpClient client = new HQHttpClient(keystoreConfig, config, keystoreConfig.isAcceptUnverifiedCert());
    HttpParams params = client.getParams();
    params.setParameter(CoreProtocolPNames.USER_AGENT, useragent.get());
    if (this.hosthdr != null) {
        params.setParameter(ClientPNames.VIRTUAL_HOST, this.hosthdr);
    }
    HttpRequestBase request;
    double avail = 0;
    try {
        if (getMethod().equals(HttpHead.METHOD_NAME)) {
            request = new HttpHead(getURL());
            addParams(request, this.params.get());
        } else if (getMethod().equals(HttpPost.METHOD_NAME)) {
            HttpPost httpPost = new HttpPost(getURL());
            request = httpPost;
            addParams(httpPost, this.params.get());
        } else {
            request = new HttpGet(getURL());
            addParams(request, this.params.get());
        }
        request.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, isFollow());
        addCredentials(request, client);
        startTime();
        HttpResponse response = client.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        int tries = 0;
        while (statusCode == HttpURLConnection.HTTP_MOVED_TEMP && tries < 3) {
            tries++;
            Header header = response.getFirstHeader("Location");
            String url = header.getValue();
            String[] toks = url.split(";");
            String[] t = toks.length > 1 ? toks[1].split("\\?") : new String[0];
            response = getRedirect(toks[0], t.length > 1 ? t[1] : "");
            statusCode = response.getStatusLine().getStatusCode();
        }
        endTime();
        setResponseCode(statusCode);
        avail = getAvail(statusCode);
        StringBuilder msg = new StringBuilder(String.valueOf(statusCode));
        Header header = response.getFirstHeader("Server");
        msg.append(header != null ? " (" + header.getValue() + ")" : "");
        setLastModified(response, statusCode);
        avail = checkPattern(response, avail, msg);
        setAvailMsg(avail, msg);
    } catch (UnsupportedEncodingException e) {
        log.error("unsupported encoding: " + e, e);
    } catch (IOException e) {
        avail = Metric.AVAIL_DOWN;
        setErrorMessage(e.toString());
    } finally {
        setAvailability(avail);
    }
    netstat();
}

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

static Request forceMerge(ForceMergeRequest forceMergeRequest) {
    String[] indices = forceMergeRequest.indices() == null ? Strings.EMPTY_ARRAY : forceMergeRequest.indices();
    Request request = new Request(HttpPost.METHOD_NAME, endpoint(indices, "_forcemerge"));

    Params parameters = new Params(request);
    parameters.withIndicesOptions(forceMergeRequest.indicesOptions());
    parameters.putParam("max_num_segments", Integer.toString(forceMergeRequest.maxNumSegments()));
    parameters.putParam("only_expunge_deletes", Boolean.toString(forceMergeRequest.onlyExpungeDeletes()));
    parameters.putParam("flush", Boolean.toString(forceMergeRequest.flush()));
    return request;
}

From source file:org.jtalks.poulpe.service.JcommuneHttpNotifier.java

/**
 * Creates HTTP request based on the specified method.
 *
 * @param httpMethod either {@link HttpDelete#getMethod()} or {@link HttpPost#getMethod()}
 * @param url        address of JCommune
 * @return constructed HTTP request based on specified method
 * @throws IllegalArgumentException if the method was neither DELETE nor POST
 *//*  ww w  . j  a va  2s. c  o  m*/
private HttpRequestBase createWithHttpMethod(String httpMethod, String url) {
    if (HttpDelete.METHOD_NAME.equals(httpMethod)) {
        return new HttpDelete(url);
    } else if (HttpPost.METHOD_NAME.equals(httpMethod)) {
        return new HttpPost(url);
    } else {
        throw new IllegalArgumentException("Wrong HTTP method name was specified: [" + httpMethod + "]");
    }
}