Example usage for org.apache.http.client.fluent Request Post

List of usage examples for org.apache.http.client.fluent Request Post

Introduction

In this page you can find the example usage for org.apache.http.client.fluent Request Post.

Prototype

public static Request Post(final String uri) 

Source Link

Usage

From source file:com.ykun.commons.utils.http.HttpClientUtils.java

public static String post(String url, Header[] headers, Map<String, String> params) {
    return execute(Request.Post(url).bodyForm(map2List(params), Consts.UTF_8).setHeaders(headers));
}

From source file:com.softinstigate.restheart.integrationtest.PostCollectionIT.java

@Test
public void testPostCollection() throws Exception {
    try {/*from w  ww  .j a v a 2 s  . c o  m*/
        Response resp;

        // *** PUT tmpdb
        resp = adminExecutor.execute(Request.Put(dbTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check put db", resp, HttpStatus.SC_CREATED);

        // *** PUT tmpcoll
        resp = adminExecutor.execute(Request.Put(collectionTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check put coll1", resp, HttpStatus.SC_CREATED);

        resp = adminExecutor.execute(Request.Post(collectionTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check post coll1", resp, HttpStatus.SC_CREATED);

        // *** POST tmpcoll
        resp = adminExecutor.execute(Request.Post(collectionTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        HttpResponse httpResp = check("check post coll1 again", resp, HttpStatus.SC_CREATED);

        Header[] headers = httpResp.getHeaders(Headers.LOCATION_STRING);

        assertNotNull("check loocation header", headers);
        assertTrue("check loocation header", headers.length > 0);

        Header locationH = headers[0];
        String location = locationH.getValue();

        URI createdDocUri = URI.create(location);

        resp = adminExecutor.execute(Request.Get(createdDocUri).addHeader(Headers.CONTENT_TYPE_STRING,
                Representation.HAL_JSON_MEDIA_TYPE));

        JsonObject content = JsonObject.readFrom(resp.returnContent().asString());
        assertNotNull("check created doc content", content.get("_id"));
        assertNotNull("check created doc content", content.get("_etag"));
        assertNotNull("check created doc content", content.get("a"));
        assertTrue("check created doc content", content.get("a").asInt() == 1);

        String _id = content.get("_id").asString();
        String _etag = content.get("_etag").asString();

        // try to post with _id without etag
        resp = adminExecutor
                .execute(Request.Post(collectionTmpUri).bodyString("{_id:\"" + _id + "\", a:1}", halCT)
                        .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check post created doc without etag", resp, HttpStatus.SC_CONFLICT);

        // try to post with wrong etag
        resp = adminExecutor
                .execute(Request.Post(collectionTmpUri).bodyString("{_id:\"" + _id + "\", a:1}", halCT)
                        .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE)
                        .addHeader(Headers.IF_MATCH_STRING, "pippoetag"));
        check("check put created doc with wrong etag", resp, HttpStatus.SC_PRECONDITION_FAILED);

        // try to post with correct etag
        resp = adminExecutor
                .execute(Request.Post(collectionTmpUri).bodyString("{_id:\"" + _id + "\", a:1}", halCT)
                        .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE)
                        .addHeader(Headers.IF_MATCH_STRING, _etag));
        check("check post created doc with correct etag", resp, HttpStatus.SC_OK);
    } finally {
        mongoClient.dropDatabase(dbTmpName);
    }
}

From source file:com.preferanser.server.client.DealUploader.java

private void start() throws IOException {
    for (File jsonFile : jsonFiles) {
        logger.info("Posting json from file {} ...", jsonFile);
        HttpResponse response = Request.Post(url).addHeader("Cookie", authCookie)
                .bodyFile(jsonFile, ContentType.APPLICATION_JSON).execute().returnResponse();
        logger.info("Response: {}", response);
    }//  w w w  . ja v  a 2s. c o  m
}

From source file:com.twosigma.beaker.core.rest.PublishRest.java

@POST
@Path("github")
@Produces(MediaType.APPLICATION_JSON)//  w ww . j ava  2 s  .  c  om
public String notebook(@FormParam("json") String json, @FormParam("type") String type)
        throws IOException, ClientProtocolException {
    String files = "{\"Beaker Share\":{\"content\":\"" + JSONObject.escape(json) + "\"}}";
    String body = "{\"description\":\"Beaker Share\",\"public\":true,\"files\":" + files + "}\n";
    String response = null;
    try {
        response = Request.Post(this.gistUrl).useExpectContinue().version(HttpVersion.HTTP_1_1)
                .bodyString(body, ContentType.APPLICATION_JSON).execute().returnContent().asString();
    } catch (Throwable t) {
        throw new GistPublishException(ExceptionUtils.getStackTrace(t));
    }
    JSONObject parsed = (JSONObject) JSONValue.parse(response);
    String githubUrl = (String) parsed.get("html_url");
    int slash = githubUrl.lastIndexOf("/");
    if (slash < 0) {
        System.err.println("no slash found in github url: " + githubUrl);
        return githubUrl;
    }
    return this.sharingUrl + githubUrl.substring(slash);
}

From source file:com.ctrip.infosec.rule.resource.Counter.java

/**
 * ???//w  ww  .  j  av  a 2  s  .c o  m
 *
 * @param bizNo ?
 * @return
 */
public static GetDataFieldListResponse datafieldList(String bizNo) {
    check();
    GetDataFieldListResponse response = null;
    try {
        String responseTxt = Request.Post(urlPrefix + "/rest/configs/datafieldList")
                .bodyForm(Form.form().add("bizNo", bizNo).build(), Charset.forName("UTF-8")).execute()
                .returnContent().asString();
        response = JSON.parseObject(responseTxt, GetDataFieldListResponse.class);
    } catch (Exception ex) {
        logger.error(Contexts.getLogPrefix() + "invoke Counter.datafieldList fault.", ex);
        response = new GetDataFieldListResponse();
        response.setErrorCode(ErrorCode.EXCEPTION.getCode());
        response.setErrorMessage(ex.getMessage());
    }
    return response;
}

From source file:es.upm.oeg.examples.watson.service.LanguageIdentificationService.java

public String getLang(String text) throws IOException, URISyntaxException {

    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("txt", text));
    qparams.add(new BasicNameValuePair("sid", "lid-generic"));
    qparams.add(new BasicNameValuePair("rt", "json"));

    Executor executor = Executor.newInstance().auth(username, password);

    URI serviceURI = new URI(baseURL).normalize();
    String auth = username + ":" + password;
    String resp = executor.execute(Request.Post(serviceURI)
            .addHeader("Authorization", "Basic " + Base64.encodeBase64String(auth.getBytes()))
            .bodyString(URLEncodedUtils.format(qparams, "utf-8"), ContentType.APPLICATION_FORM_URLENCODED))
            .returnContent().asString();

    JSONObject lang = JSONObject.parse(resp);

    return lang.get("lang").toString();

}

From source file:org.mule.module.http.functional.listener.HttpListenerNotificationsTestCase.java

@Test
public void receiveNotification() throws Exception {
    String listenerUrl = String.format("http://localhost:%s/%s", listenPort.getNumber(), path.getValue());

    CountDownLatch latch = new CountDownLatch(2);
    TestConnectorMessageNotificationListener listener = new TestConnectorMessageNotificationListener(latch,
            listenerUrl);//from   w w w.j  a v  a  2  s  .  c  o m
    muleContext.getNotificationManager().addListener(listener);

    Request.Post(listenerUrl).execute();

    latch.await(1000, TimeUnit.MILLISECONDS);

    assertThat(listener.getNotificationActionNames(),
            contains(getActionName(MESSAGE_RECEIVED), getActionName(MESSAGE_RESPONSE)));
}

From source file:com.qwazr.graph.test.FullTest.java

@Test
public void test000CreateDatabase() throws IOException {

    HashMap<String, PropertyTypeEnum> node_properties = new HashMap<String, PropertyTypeEnum>();
    node_properties.put("type", PropertyTypeEnum.indexed);
    node_properties.put("date", PropertyTypeEnum.indexed);
    node_properties.put("name", PropertyTypeEnum.stored);
    node_properties.put("user", PropertyTypeEnum.stored);
    HashSet<String> edge_types = new HashSet<String>();
    edge_types.add("see");
    edge_types.add("buy");
    GraphDefinition graphDef = new GraphDefinition(node_properties, edge_types);

    HttpResponse response = Request.Post(BASE_URL + '/' + TEST_BASE)
            .bodyString(JsonMapper.MAPPER.writeValueAsString(graphDef), ContentType.APPLICATION_JSON)
            .connectTimeout(60000).socketTimeout(60000).execute().returnResponse();
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
}

From source file:com.qwazr.cluster.client.ClusterSingleClient.java

@Override
public ClusterNodeStatusJson register(ClusterNodeJson register) {
    UBuilder uriBuilder = new UBuilder("/cluster");
    Request request = Request.Post(uriBuilder.build());
    return commonServiceRequest(request, register, null, ClusterNodeStatusJson.class, 200);
}

From source file:org.n52.iceland.skeleton.Base.java

public String pox(String filename) throws IOException {
    URL url = Resources.getResource("requests/" + filename);
    InputStream request = Resources.asByteSource(url).openBufferedStream();
    return Request.Post(getEndpointURL()).bodyStream(request, ContentType.APPLICATION_XML).execute()
            .returnContent().asString();
}