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:org.deviceconnect.android.manager.setting.ReqResDebugActivity.java

/**
 * Http?./*w ww  .j  av  a  2 s  . c o  m*/
 * @param method HTTP
 * @param uri ?URI
 * @param listener Http????
 */
private void executeHttpRequest(final String method, final URI uri, final HttpListener listener) {
    HttpUriRequest req = null;
    if (HttpGet.METHOD_NAME.equals(method)) {
        req = new HttpGet(uri.toString());
    } else if (HttpPost.METHOD_NAME.equals(method)) {
        req = new HttpPost(uri.toString());
    } else if (HttpPut.METHOD_NAME.equals(method)) {
        req = new HttpPut(uri.toString());
    } else if (HttpDelete.METHOD_NAME.equals(method)) {
        req = new HttpDelete(uri.toString());
    } else if ("?".equals(method)) {
        AssetManager manager = getAssets();
        try {
            // TODO ??????
            String name = "test.png";

            MultipartEntity entity = new MultipartEntity();
            InputStream in = manager.open(name);
            // ??
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len;
            byte[] buf = new byte[4096];
            while ((len = in.read(buf)) > 0) {
                baos.write(buf, 0, len);
            }
            // ?
            entity.addPart(FileProfileConstants.PARAM_DATA, new BinaryBody(baos.toByteArray(), name));

            req = new HttpPost(uri.toString());
            ((HttpPost) req).setEntity(entity);
        } catch (UnsupportedEncodingException e) {
            return;
        } catch (IOException e) {
            return;
        }
    } else {
        return;
    }

    if (req != null) {
        executeHttpRequest(req, listener);
    }
}

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

public void testInvokeHeadersEcho() throws Throwable {

    // Container to store callback's results and do the asserts.
    final ResultsContainer container = new ResultsContainer();
    final List<Pair<String, String>> headers = new ArrayList<Pair<String, String>>();
    final List<String> headerNames = new ArrayList<String>();

    for (int i = 0; i < 10; i++) {
        String name;/*from w  w  w  .  jav a 2  s  .  c o  m*/

        do {
            name = UUID.randomUUID().toString();
        } while (headerNames.contains(name));

        headers.add(new Pair<String, String>(name, UUID.randomUUID().toString()));
        headerNames.add(name);
    }

    MobileServiceClient client = null;
    try {
        client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext());

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

        List<Pair<String, String>> fakeParameters = new ArrayList<Pair<String, String>>();

        ServiceFilterResponse response = client
                .invokeApi("myApi", null, HttpPost.METHOD_NAME, headers, fakeParameters).get();

        if (response == null || response.getContent() == null) {
            container.setException(new Exception("Expected response"));
        } else {
            container.setResponseValue(response.getContent());
        }

    } catch (Exception exception) {
        container.setException(exception);
    }

    // Asserts
    Exception exception = container.getException();
    if (exception != null) {
        fail(exception.getMessage());
    } else {
        JsonObject jResponse = (new JsonParser()).parse(container.getResponseValue()).getAsJsonObject();

        if (jResponse.has("headers") && jResponse.get("headers").isJsonObject()) {
            JsonObject jHeaders = jResponse.getAsJsonObject("headers");

            for (Pair<String, String> header : headers) {
                if (jHeaders.has(header.first)) {
                    assertEquals(header.second, jHeaders.get(header.first).getAsString());
                } else {
                    fail("Expected header.");
                }
            }

        } else {
            fail("Expected headers.");
        }

    }
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.tests.CustomApiTests.java

private TestCase createJsonApiTest(final ApiPermissions permission, final boolean isAuthenticated,
        final Random rndGen, int testNumber) {

    String name = String.format("Json Overload - %s - authenticated=%s - Instance=%s", permission.toString(),
            isAuthenticated, testNumber + 1);

    TestCase test = new TestCase(name) {
        MobileServiceClient mClient;/*from  ww w .j  a va 2 s.com*/
        List<Pair<String, String>> mQuery;
        boolean mExpected401;
        TestResult mResult;

        @Override
        protected void executeTest(MobileServiceClient client, TestExecutionCallback callback) {
            mResult = new TestResult();
            mResult.setTestCase(this);
            mResult.setStatus(TestStatus.Passed);

            if (permission == ApiPermissions.Public) {
                client = client.withFilter(new RemoveAuthenticationServiceFilter());
            }

            mExpected401 = permission == ApiPermissions.Admin
                    || (permission == ApiPermissions.User && !isAuthenticated);
            mClient = client;

            String method = createHttpMethod(rndGen);
            log("Method = " + method);

            JsonElement body = null;
            if (!method.equals(HttpGet.METHOD_NAME) && !method.equals(HttpDelete.METHOD_NAME)) {
                if (method.equals(PATCH_METHOD_NAME) || method.equals(HttpPut.METHOD_NAME)) {
                    body = createJson(rndGen, 0, false);
                } else {
                    body = createJson(rndGen, 0, true);
                }
            }

            if (body == null) {
                log("Body: NULL");
            } else {
                log("Body: " + body.toString());
            }

            mQuery = createQuery(rndGen);

            JsonElement queryJson = createQueryObject(mQuery);
            log("Query: " + queryJson.toString());

            String api = apiNames.get(permission);
            log("API: " + api);

            if (body == null && method.equals(HttpPost.METHOD_NAME) && mQuery == null) {

                try {
                    JsonElement jsonElement = client.invokeApi(api).get();

                    JsonObject expectedResult = new JsonObject();
                    expectedResult.add("user", createUserObject(mClient));

                    if (mQuery != null && mQuery.size() > 0) {
                        expectedResult.add("query", createQueryObject(mQuery));
                    }

                    if (!Util.compareJson(expectedResult, jsonElement)) {
                        createResultFromException(mResult,
                                new ExpectedValueException(expectedResult, jsonElement));
                    }
                } catch (Exception exception) {
                    MobileServiceException cause = (MobileServiceException) exception.getCause();

                    ServiceFilterResponse response = cause.getResponse();

                    if (mExpected401) {
                        if (response == null || response.getStatus().getStatusCode() != 401) {
                            mResult.setStatus(TestStatus.Failed);
                            mResult.setException(exception);
                            mResult.getTestCase().log("Expected 401");
                        }
                    } else {
                        if (exception != null) {
                            createResultFromException(mResult, exception);
                        }
                    }
                }

            } else if (body != null && method.equals(HttpPost.METHOD_NAME) && mQuery == null) {
                try {
                    JsonElement jsonElement = client.invokeApi(api, body).get();

                    JsonObject expectedResult = new JsonObject();
                    expectedResult.add("user", createUserObject(mClient));

                    if (mQuery != null && mQuery.size() > 0) {
                        expectedResult.add("query", createQueryObject(mQuery));
                    }

                    if (!Util.compareJson(expectedResult, jsonElement)) {
                        createResultFromException(mResult,
                                new ExpectedValueException(expectedResult, jsonElement));
                    }
                } catch (Exception exception) {
                    if (mExpected401) {
                        MobileServiceException cause = (MobileServiceException) exception.getCause();

                        ServiceFilterResponse response = cause.getResponse();

                        if (response == null || response.getStatus().getStatusCode() != 401) {
                            mResult.setStatus(TestStatus.Failed);
                            mResult.setException(exception);
                            mResult.getTestCase().log("Expected 401");
                        }
                    } else {
                        if (exception != null) {
                            createResultFromException(mResult, exception);
                        }
                    }
                }

            } else if (body == null) {

                try {
                    JsonElement jsonElement = client.invokeApi(api, method, mQuery).get();

                    JsonObject expectedResult = new JsonObject();
                    expectedResult.add("user", createUserObject(mClient));

                    if (mQuery != null && mQuery.size() > 0) {
                        expectedResult.add("query", createQueryObject(mQuery));
                    }

                    if (!Util.compareJson(expectedResult, jsonElement)) {
                        createResultFromException(mResult,
                                new ExpectedValueException(expectedResult, jsonElement));
                    }
                } catch (Exception exception) {
                    if (mExpected401) {
                        MobileServiceException cause = (MobileServiceException) exception.getCause();

                        ServiceFilterResponse response = cause.getResponse();

                        if (response == null || response.getStatus().getStatusCode() != 401) {
                            mResult.setStatus(TestStatus.Failed);
                            mResult.setException(exception);
                            mResult.getTestCase().log("Expected 401");
                        }
                    } else {
                        if (exception != null) {
                            createResultFromException(mResult, (Exception) exception.getCause());
                        }
                    }
                }

            } else {

                try {
                    JsonElement jsonElement = client.invokeApi(api, body, method, mQuery).get();

                    JsonObject expectedResult = new JsonObject();
                    expectedResult.add("user", createUserObject(mClient));

                    if (mQuery != null && mQuery.size() > 0) {
                        expectedResult.add("query", createQueryObject(mQuery));
                    }

                    if (!Util.compareJson(expectedResult, jsonElement)) {
                        createResultFromException(mResult,
                                new ExpectedValueException(expectedResult, jsonElement));
                    }
                } catch (Exception exception) {
                    if (mExpected401) {
                        MobileServiceException cause = (MobileServiceException) exception.getCause();

                        ServiceFilterResponse response = cause.getResponse();

                        if (response == null || response.getStatus().getStatusCode() != 401) {
                            mResult.setStatus(TestStatus.Failed);
                            mResult.setException(exception);
                            mResult.getTestCase().log("Expected 401");
                        }
                    } else {
                        if (exception != null) {
                            createResultFromException(mResult, (Exception) exception.getCause());
                        }
                    }
                }
            }

            if (callback != null)
                callback.onTestComplete(this, mResult);
        }
    };

    return test;
}

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

public void testInvokeParametersEcho() throws Throwable {

    // Container to store callback's results and do the asserts.
    final ResultsContainer container = new ResultsContainer();
    final List<Pair<String, String>> parameters = new ArrayList<Pair<String, String>>();
    final List<String> parameterNames = new ArrayList<String>();

    for (int i = 0; i < 10; i++) {
        String name;/*from  w  ww  .j  ava  2  s .c  om*/

        do {
            name = UUID.randomUUID().toString();
        } while (parameterNames.contains(name));

        parameters.add(new Pair<String, String>(name, UUID.randomUUID().toString()));
        parameterNames.add(name);
    }

    MobileServiceClient client = null;
    try {
        client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext());

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

        ServiceFilterResponse response = client.invokeApi("myApi", null, HttpPost.METHOD_NAME, null, parameters)
                .get();

        if (response == null || response.getContent() == null) {
            container.setException(new Exception("Expected response"));
        } else {
            container.setResponseValue(response.getContent());
        }

    } catch (Exception exception) {
        container.setException(exception);
    }

    // Asserts
    Exception exception = container.getException();
    if (exception != null) {
        fail(exception.getMessage());
    } else {
        JsonObject jResponse = (new JsonParser()).parse(container.getResponseValue()).getAsJsonObject();

        if (jResponse.has("parameters") && jResponse.get("parameters").isJsonObject()) {
            JsonObject jParameters = jResponse.getAsJsonObject("parameters");

            for (Pair<String, String> parameter : parameters) {
                if (jParameters.has(parameter.first)) {
                    assertEquals(parameter.second, jParameters.get(parameter.first).getAsString());
                } else {
                    fail("Expected parameter.");
                }
            }

        } else {
            fail("Expected parameters.");
        }
    }
}

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

public void testRefresh() {
    String[] indices = randomBoolean() ? null : randomIndicesNames(0, 5);
    RefreshRequest refreshRequest;/*  ww  w.  j a  va2 s . c  om*/
    if (randomBoolean()) {
        refreshRequest = new RefreshRequest(indices);
    } else {
        refreshRequest = new RefreshRequest();
        refreshRequest.indices(indices);
    }
    Map<String, String> expectedParams = new HashMap<>();
    setRandomIndicesOptions(refreshRequest::indicesOptions, refreshRequest::indicesOptions, expectedParams);
    Request request = RequestConverters.refresh(refreshRequest);
    StringJoiner endpoint = new StringJoiner("/", "/", "");
    if (indices != null && indices.length > 0) {
        endpoint.add(String.join(",", indices));
    }
    endpoint.add("_refresh");
    assertThat(request.getEndpoint(), equalTo(endpoint.toString()));
    assertThat(request.getParameters(), equalTo(expectedParams));
    assertThat(request.getEntity(), nullValue());
    assertThat(request.getMethod(), equalTo(HttpPost.METHOD_NAME));
}

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

public void testFlush() {
    String[] indices = randomBoolean() ? null : randomIndicesNames(0, 5);
    FlushRequest flushRequest;/*w w  w.  ja va2 s.  co m*/
    if (randomBoolean()) {
        flushRequest = new FlushRequest(indices);
    } else {
        flushRequest = new FlushRequest();
        flushRequest.indices(indices);
    }
    Map<String, String> expectedParams = new HashMap<>();
    setRandomIndicesOptions(flushRequest::indicesOptions, flushRequest::indicesOptions, expectedParams);
    if (randomBoolean()) {
        flushRequest.force(randomBoolean());
    }
    expectedParams.put("force", Boolean.toString(flushRequest.force()));
    if (randomBoolean()) {
        flushRequest.waitIfOngoing(randomBoolean());
    }
    expectedParams.put("wait_if_ongoing", Boolean.toString(flushRequest.waitIfOngoing()));

    Request request = RequestConverters.flush(flushRequest);
    StringJoiner endpoint = new StringJoiner("/", "/", "");
    if (indices != null && indices.length > 0) {
        endpoint.add(String.join(",", indices));
    }
    endpoint.add("_flush");
    assertThat(request.getEndpoint(), equalTo(endpoint.toString()));
    assertThat(request.getParameters(), equalTo(expectedParams));
    assertThat(request.getEntity(), nullValue());
    assertThat(request.getMethod(), equalTo(HttpPost.METHOD_NAME));
}

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

static Request rollover(RolloverRequest rolloverRequest) throws IOException {
    String endpoint = new EndpointBuilder().addPathPart(rolloverRequest.getAlias()).addPathPartAsIs("_rollover")
            .addPathPart(rolloverRequest.getNewIndexName()).build();
    Request request = new Request(HttpPost.METHOD_NAME, endpoint);

    Params params = new Params(request);
    params.withTimeout(rolloverRequest.timeout());
    params.withMasterTimeout(rolloverRequest.masterNodeTimeout());
    params.withWaitForActiveShards(rolloverRequest.getCreateIndexRequest().waitForActiveShards());
    if (rolloverRequest.isDryRun()) {
        params.putParam("dry_run", Boolean.TRUE.toString());
    }/*from   ww  w. jav  a2 s. co m*/

    request.setEntity(createEntity(rolloverRequest, REQUEST_BODY_CONTENT_TYPE));
    return request;
}

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

public void testSyncedFlush() {
    String[] indices = randomBoolean() ? null : randomIndicesNames(0, 5);
    SyncedFlushRequest syncedFlushRequest;
    if (randomBoolean()) {
        syncedFlushRequest = new SyncedFlushRequest(indices);
    } else {/*from  ww w  . j a v  a2 s. c o  m*/
        syncedFlushRequest = new SyncedFlushRequest();
        syncedFlushRequest.indices(indices);
    }
    Map<String, String> expectedParams = new HashMap<>();
    setRandomIndicesOptions(syncedFlushRequest::indicesOptions, syncedFlushRequest::indicesOptions,
            expectedParams);
    Request request = RequestConverters.flushSynced(syncedFlushRequest);
    StringJoiner endpoint = new StringJoiner("/", "/", "");
    if (indices != null && indices.length > 0) {
        endpoint.add(String.join(",", indices));
    }
    endpoint.add("_flush/synced");
    assertThat(request.getEndpoint(), equalTo(endpoint.toString()));
    assertThat(request.getParameters(), equalTo(expectedParams));
    assertThat(request.getEntity(), nullValue());
    assertThat(request.getMethod(), equalTo(HttpPost.METHOD_NAME));
}

From source file:com.codeim.coxin.fanfou.Weibo.java

/****
 * /*from w  w w.ja v a2 s .  c  o m*/
 * @param info_or_comment:  1: info; 2: comment
 * @param status
 * @param file
 * @return
 * @throws HttpException
 */
public Photo uploadPhoto(int info_or_comment, String status, File file) throws HttpException {
    return new Photo(http.httpRequestImage(getBaseURL() + "flymsg/sendphoto.php",
            createParams(new BasicNameValuePair("INFO_OR_COMMENT", String.valueOf(info_or_comment)),
                    new BasicNameValuePair("status", status), new BasicNameValuePair("source", source)),
            file, false, HttpPost.METHOD_NAME));
}

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

public void testForceMerge() {
    String[] indices = randomBoolean() ? null : randomIndicesNames(0, 5);
    ForceMergeRequest forceMergeRequest;
    if (randomBoolean()) {
        forceMergeRequest = new ForceMergeRequest(indices);
    } else {/*w w  w. j  a  va 2 s. co m*/
        forceMergeRequest = new ForceMergeRequest();
        forceMergeRequest.indices(indices);
    }

    Map<String, String> expectedParams = new HashMap<>();
    setRandomIndicesOptions(forceMergeRequest::indicesOptions, forceMergeRequest::indicesOptions,
            expectedParams);
    if (randomBoolean()) {
        forceMergeRequest.maxNumSegments(randomInt());
    }
    expectedParams.put("max_num_segments", Integer.toString(forceMergeRequest.maxNumSegments()));
    if (randomBoolean()) {
        forceMergeRequest.onlyExpungeDeletes(randomBoolean());
    }
    expectedParams.put("only_expunge_deletes", Boolean.toString(forceMergeRequest.onlyExpungeDeletes()));
    if (randomBoolean()) {
        forceMergeRequest.flush(randomBoolean());
    }
    expectedParams.put("flush", Boolean.toString(forceMergeRequest.flush()));

    Request request = RequestConverters.forceMerge(forceMergeRequest);
    StringJoiner endpoint = new StringJoiner("/", "/", "");
    if (indices != null && indices.length > 0) {
        endpoint.add(String.join(",", indices));
    }
    endpoint.add("_forcemerge");
    assertThat(request.getEndpoint(), equalTo(endpoint.toString()));
    assertThat(request.getParameters(), equalTo(expectedParams));
    assertThat(request.getEntity(), nullValue());
    assertThat(request.getMethod(), equalTo(HttpPost.METHOD_NAME));
}