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:org.wisdom.framework.vertx.FormTest.java

@Test
public void testFormSubmissionAsFormURLEncoded() throws InterruptedException, IOException {
    Router router = prepareServer();/*from  w w w. ja  v  a 2 s. c  o  m*/

    // Prepare the router with a controller
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result submit() {
            final Map<String, List<String>> form = context().form();
            // String
            if (!form.get("key").get(0).equals("value")) {
                return badRequest("key is not equals to value");
            }

            // Multiple values
            List<String> list = form.get("list");
            if (!(list.contains("1") && list.contains("2"))) {
                return badRequest("list does not contains 1 and 2");
            }

            return ok(context().header(HeaderNames.CONTENT_TYPE));
        }
    };
    Route route = new RouteBuilder().route(HttpMethod.POST).on("/").to(controller, "submit");
    when(router.getRouteFor(anyString(), anyString(), any(org.wisdom.api.http.Request.class)))
            .thenReturn(route);

    server.start();
    waitForStart(server);

    int port = server.httpPort();

    final HttpResponse response = Request.Post("http://localhost:" + port + "/")
            .bodyForm(Form.form().add("key", "value").add("list", "1").add("list", "2").build()).execute()
            .returnResponse();

    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
    assertThat(EntityUtils.toString(response.getEntity())).contains(MimeTypes.FORM);
}

From source file:io.gravitee.gateway.standalone.PostContentGatewayTest.java

@Test
public void call_case1_chunked_request() throws Exception {
    String testCase = "case1";

    InputStream is = this.getClass().getClassLoader().getResourceAsStream(testCase + "/request_content.json");
    Request request = Request.Post("http://localhost:8082/test/my_team?case=" + testCase).bodyStream(is,
            ContentType.APPLICATION_JSON);

    try {/*from w ww  .j  av  a2  s.  c o m*/
        Response response = request.execute();

        HttpResponse returnResponse = response.returnResponse();
        assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode());

        // Not a chunked response because body content is to small
        assertEquals(null, returnResponse.getFirstHeader(HttpHeaders.TRANSFER_ENCODING));
    } catch (Exception e) {
        e.printStackTrace();
        assertTrue(false);
    }
}

From source file:com.m3958.apps.anonymousupload.integration.java.FileUploadTest.java

@Test
public void testPostNone() throws ClientProtocolException, IOException, URISyntaxException {

    File f = new File("README.md");

    Assert.assertTrue(f.exists());//  w w  w.j  a v  a  2 s.co  m

    String c = Request.Post(new URIBuilder().setScheme("http").setHost("localhost").setPort(8080).build())
            .body(MultipartEntityBuilder.create().addTextBody("fn", "abcfn.md").build()).execute()
            .returnContent().asString();

    String url = c.trim();
    Assert.assertEquals("1", url);

    testComplete();
}

From source file:es.uvigo.esei.dai.hybridserver.utils.TestUtils.java

/**
 * Realiza una peticin por POST y devuelve el contenido de la respuesta.
 * //from www . j av a  2  s. com
 * La peticin se hace en UTF-8 y solicitando el cierre de la conexin.
 * 
 * Este mtodo comprueba que el cdigo de respuesta HTTP sea 200 OK.
 * 
 * @param url URL de la pgina solicitada.
 * @param content parmetros que se incluirn en la peticin HTTP.
 * @return contenido de la respuesta HTTP.
 * @throws IOException en el caso de que se produzca un error de conexin.
 */
public static String postContent(String url, Map<String, String> content) throws IOException {
    final HttpResponse response = Request.Post(url).addHeader("Connection", "close")
            .addHeader("Content-encoding", "UTF-8").bodyForm(mapToNameValuePair(content)).execute()
            .returnResponse();

    assertEquals(200, response.getStatusLine().getStatusCode());

    return EntityUtils.toString(response.getEntity());
}

From source file:org.restheart.test.performance.LoadPutPT.java

/**
 *
 * @throws IOException//  ww w . jav a2s .  c  o  m
 */
public void put() throws Exception {
    BasicDBObject content = new BasicDBObject("random", Math.random());

    Response resp = httpExecutor.execute(Request.Post(url).bodyString(content.toString(), halCT)
            .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));

    HttpResponse httpResp = resp.returnResponse();
    assertNotNull(httpResp);
    HttpEntity entity = httpResp.getEntity();
    assertNotNull(entity);
    StatusLine statusLine = httpResp.getStatusLine();
    assertNotNull(statusLine);

    assertEquals("check status code", HttpStatus.SC_CREATED, statusLine.getStatusCode());
}

From source file:com.github.piotrkot.resources.CompilerResource.java

/**
 * Upload source for compiler./* w  ww. j  a  va  2s .c  o m*/
 * @param user Logged in user.
 * @param stream File input stream.
 * @param details Form data details.
 * @return Compiler result view.
 */
@Path("/source")
@POST
@Timed
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_HTML)
public Response uploadSource(@Auth final User user, @FormDataParam("inputFile") final InputStream stream,
        @FormDataParam("inputFile") final FormDataContentDisposition details) {
    Response response = Response.serverError().build();
    try {
        final String request = Request.Post(String.format("%s/source", this.conf.getCompiler()))
                .setHeader(this.authorization(user))
                .body(MultipartEntityBuilder.create()
                        .addBinaryBody("file", stream, ContentType.DEFAULT_BINARY, details.getName()).build())
                .execute().returnContent().asString();
        response = Response.seeOther(URI.create(String.format("/compiler/result/%s", request))).build();
    } catch (final IOException ex) {
        log.error("Cannot connect to the server", ex);
    }
    return response;
}

From source file:com.qwazr.crawler.web.client.WebCrawlerSingleClient.java

@Override
public WebCrawlStatus runSession(String session_name, WebCrawlDefinition crawlDefinition) {
    UBuilder uriBuilder = new UBuilder("/crawler/web/sessions/", session_name);
    Request request = Request.Post(uriBuilder.build());
    return commonServiceRequest(request, crawlDefinition, null, WebCrawlStatus.class, 200, 202);
}

From source file:hulop.cm.util.LogHelper.java

public JSONArray getLog(String clientId, String start, String end, String skip, String limit) throws Exception {
    if (mApiKey == null) {
        return new JSONArray();
    }//ww  w .  ja  va 2s. c  o  m
    Form form = Form.form().add("action", "get").add("auditor_api_key", mApiKey).add("event", "conversation");
    if (clientId != null) {
        form.add("clientId", clientId);
    }
    if (start != null) {
        form.add("start", start);
    }
    if (end != null) {
        form.add("end", end);
    }
    if (skip != null) {
        form.add("skip", skip);
    }
    if (limit != null) {
        form.add("limit", limit);
    }
    Request request = Request.Post(new URI(mEndpoint)).bodyForm(form.build());
    return (new JSONArray(request.execute().returnContent().asString()));
}

From source file:de.elomagic.carafile.server.bl.RegistryClientBean.java

/**
 * Register a chunk of a file at the registry.
 *
 * @param chunkHash SHA-1 hash of the chunk
 * @throws IOException Thrown when unable to call REST service at the registry
 *//*from w  ww  .ja  v  a 2s .c o m*/
public void registerChunk(final String chunkHash) throws IOException {
    LOG.debug("Registering chunk at registry");

    URI own = UriBuilder.fromUri(ownPeerURI).build();

    if (ownPeerURI.equals(registryURI)) {
        registryBean.registerChunk(chunkHash, own);
    } else {
        URI restURI = UriBuilder.fromUri(registryURI).path(REGISTRY).path("registerChunk").path(chunkHash)
                .path(URLEncoder.encode(ownPeerURI, "utf-8")).build();

        Request.Post(restURI).execute();
    }
}

From source file:aiai.ai.station.actors.UploadResourceActor.java

public void fixedDelay() {
    if (globals.isUnitTesting) {
        return;//from   w  w w.  j ava2  s. c  o m
    }
    if (!globals.isStationEnabled) {
        return;
    }

    UploadResourceTask task;
    List<UploadResourceTask> repeat = new ArrayList<>();
    while ((task = poll()) != null) {
        boolean isOk = false;
        try (InputStream is = new FileInputStream(task.file)) {
            log.info("Start uploading result data to server, resultDataFile: {}", task.file);

            final String uri = globals.uploadRestUrl + '/' + task.taskId;
            HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .setCharset(StandardCharsets.UTF_8)
                    .addBinaryBody("file", is, ContentType.MULTIPART_FORM_DATA, task.file.getName()).build();

            Request request = Request.Post(uri).connectTimeout(5000).socketTimeout(5000).body(entity);

            Response response;
            if (globals.isSecureRestUrl) {
                response = executor.executor.execute(request);
            } else {
                response = request.execute();
            }
            String json = response.returnContent().asString();

            UploadResult result = fromJson(json);
            log.info("'\tresult data was successfully uploaded");
            if (!result.isOk) {
                log.error("Error uploading file, server error: " + result.error);
            }
            isOk = result.isOk;
        } catch (HttpResponseException e) {
            log.error("Error uploading code", e);
        } catch (SocketTimeoutException e) {
            log.error("SocketTimeoutException", e.toString());
        } catch (IOException e) {
            log.error("IOException", e);
        } catch (Throwable th) {
            log.error("Throwable", th);
        }
        if (!isOk) {
            log.error("'\tTask assigned one more time.");
            repeat.add(task);
        }

    }
    for (UploadResourceTask uploadResourceTask : repeat) {
        add(uploadResourceTask);
    }
}