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.kie.remote.tests.base.RestUtil.java

public static <T> T postEntity(URL deploymentUrl, String relativeUrl, String mediaType, int status, String user,
        String password, Object entity, Class<T>... responseTypes) {
    String uriStr = createBaseUriString(deploymentUrl, relativeUrl);

    ResponseHandler<T> rh = createResponseHandler(mediaType, status, responseTypes);

    String entityStr = ((AbstractResponseHandler) rh).serialize(entity);
    HttpEntity bodyEntity = null;//  w  ww  . ja v  a  2 s.c o  m
    try {
        bodyEntity = new StringEntity(entityStr);
    } catch (UnsupportedEncodingException uee) {
        failAndLog("Unable to encode serialized " + entity.getClass().getSimpleName() + " entity", uee);
    }

    // @formatter:off
    Request request = Request.Post(uriStr).body(bodyEntity)
            .addHeader(HttpHeaders.CONTENT_TYPE, mediaType.toString())
            .addHeader(HttpHeaders.ACCEPT, mediaType.toString())
            .addHeader(HttpHeaders.AUTHORIZATION, basicAuthenticationHeader(user, password));
    // @formatter:on

    Response resp = null;
    try {
        logOp("POST", entity, uriStr);
        resp = request.execute();
    } catch (Exception e) {
        failAndLog("[GET] " + uriStr, e);
    }

    try {
        return resp.handleResponse(rh);
    } catch (Exception e) {
        failAndLog("Failed retrieving response from [GET] " + uriStr, e);
    }

    // never happens
    return null;
}

From source file:photosharing.api.conx.RecommendationDefinition.java

/**
 * like a file//from  w  w  w.j a v  a 2  s  .  c om
 * 
 * Example URL
 * http://localhost:9080/photoSharing/api/like?r=on&lid=f8ad2a54-
 * 4d20-4b3b-ba3f-834e0b0cf90b&uid=bec24e93-8165-431d-bf38-0c668a5e6727 maps
 * to
 * https://apps.collabservdaily.swg.usma.ibm.com/files/basic/api/library/00c129c9-f3b6-4d22-9988-99e69d16d7a7/document/bf33a9b5-3042-46f0-a96e-b8742fced7a4/feed
 * 
 * 
 * @param bearer
 * @param pid
 * @param lid
 * @param nonce
 * @param response
 */
public void like(String bearer, String pid, String lid, String nonce, HttpServletResponse response) {
    String apiUrl = getApiUrl() + "/library/" + lid + "/document/" + pid + "/feed";

    try {

        String recommendation = generateRecommendationContent();
        logger.info("like -> " + apiUrl + " " + recommendation);

        // Generate the apiUrl for like
        Request post = Request.Post(apiUrl);
        post.addHeader("Authorization", "Bearer " + bearer);
        post.addHeader("X-Update-Nonce", nonce);
        post.addHeader("Content-Type", "application/atom+xml");

        ByteArrayEntity entity = new ByteArrayEntity(recommendation.getBytes("UTF-8"));
        post.body(entity);

        Executor exec = ExecutorUtil.getExecutor();
        Response apiResponse = exec.execute(post);
        HttpResponse hr = apiResponse.returnResponse();

        /**
         * Check the status codes
         */
        int code = hr.getStatusLine().getStatusCode();
        logger.info("code " + code);

        // Session is no longer valid or access token is expired
        if (code == HttpStatus.SC_FORBIDDEN) {
            response.sendRedirect("./api/logout");
        }

        // User is not authorized
        else if (code == HttpStatus.SC_UNAUTHORIZED) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        }

        // Default to SC_NO_CONTENT (204)
        else {
            response.setStatus(HttpStatus.SC_NO_CONTENT);

        }

    } catch (IOException e) {
        response.setHeader("X-Application-Error", e.getClass().getName());
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        logger.severe("IOException " + e.toString());
        e.printStackTrace();
    }
}

From source file:com.linagora.james.mailets.GuessClassificationMailet.java

@Override
public void service(Mail mail) throws MessagingException {
    try {/*w  w w. j a va  2 s.co  m*/
        String classificationGuess = executor
                .execute(Request.Post(serviceUrlWithQueryParameters(mail.getRecipients()))
                        .socketTimeout(timeoutInMs.orElse(DEFAULT_TIME))
                        .bodyString(asJson(mail), ContentType.APPLICATION_JSON))
                .returnContent().asString(StandardCharsets.UTF_8);
        addHeaders(mail, classificationGuess);
    } catch (Exception e) {
        LOGGER.error("Exception while calling Classification API", e);
    }
}

From source file:org.apache.james.jmap.methods.integration.cucumber.DownloadStepdefs.java

private void trustForBlobId(String blobId, String username) throws Exception {
    Response tokenGenerationResponse = Request
            .Post(mainStepdefs.baseUri().setPath("/download/" + blobId).build())
            .addHeader("Authorization", userStepdefs.tokenByUser.get(username).serialize()).execute();
    String serializedAttachmentAccessToken = tokenGenerationResponse.returnContent().asString();
    attachmentAccessTokens.put(new AttachmentAccessTokenKey(username, blobId),
            AttachmentAccessToken.from(serializedAttachmentAccessToken, blobId));
}

From source file:org.apache.james.jmap.methods.integration.cucumber.GetMessagesMethodStepdefs.java

private void post(String requestBody) throws Exception {
    response = Request.Post(mainStepdefs.baseUri().setPath("/jmap").build())
            .addHeader("Authorization",
                    userStepdefs.tokenByUser.get(userStepdefs.lastConnectedUser).serialize())
            .addHeader("Accept", org.apache.http.entity.ContentType.APPLICATION_JSON.getMimeType())
            .bodyString(requestBody, org.apache.http.entity.ContentType.APPLICATION_JSON).execute()
            .returnResponse();// w  w w.jav a  2s .  c om
    jsonPath = JsonPath.using(Configuration.defaultConfiguration().addOptions(Option.SUPPRESS_EXCEPTIONS))
            .parse(response.getEntity().getContent());
}

From source file:org.mule.test.construct.FlowRefTestCase.java

@Test
public void nonBlockingFlowRefToAsyncFlow() throws Exception {
    Response response = Request
            .Post(String.format("http://localhost:%s/%s", port.getNumber(), "nonBlockingFlowRefToAsyncFlow"))
            .connectTimeout(RECEIVE_TIMEOUT).bodyString(TEST_MESSAGE, ContentType.TEXT_PLAIN).execute();
    HttpResponse httpResponse = response.returnResponse();
    assertThat(httpResponse.getStatusLine().getStatusCode(), is(500));
    assertThat(IOUtils.toString(httpResponse.getEntity().getContent()),
            is("Unable to process a synchronous event asynchronously."));
}

From source file:org.kurento.orion.OrionConnector.java

/**
 * Sends a request to Orion/*from w w  w .  j  a  va 2  s. com*/
 *
 * @param ctxElement
 *          The context element
 * @param path
 *          the path from the context broker that determines which "operation"will be executed
 * @param responseClazz
 *          The class expected for the response
 * @return The object representing the JSON answer from Orion
 * @throws OrionConnectorException
 *           if a communication exception happens, either when contacting the context broker at
 *           the given address, or obtaining the answer from it.
 */
private <E, T> T sendRequestToOrion(E ctxElement, String path, Class<T> responseClazz) {
    String jsonEntity = gson.toJson(ctxElement);
    log.debug("Send request to Orion: {}", jsonEntity);

    Request req = Request.Post(this.orionAddr.toString() + path)
            .addHeader("Accept", APPLICATION_JSON.getMimeType()).bodyString(jsonEntity, APPLICATION_JSON)
            .connectTimeout(5000).socketTimeout(5000);
    Response response;
    try {
        response = req.execute();
    } catch (IOException e) {
        throw new OrionConnectorException("Could not execute HTTP request", e);
    }

    HttpResponse httpResponse = checkResponse(response);

    T ctxResp = getOrionObjFromResponse(httpResponse, responseClazz);
    log.debug("Sent to Orion. Obtained response: {}", httpResponse);

    return ctxResp;
}

From source file:net.opentsdb.search.ElasticSearch.java

public Deferred<SearchQuery> executeQuery(final SearchQuery query) {
    final Deferred<SearchQuery> result = new Deferred<SearchQuery>();

    final StringBuilder uri = new StringBuilder("http://");
    uri.append(hosts.get(0).toHostString());
    uri.append("/").append(index).append("/");
    switch (query.getType()) {
    case TSMETA:/*from  w ww. java  2 s .com*/
    case TSMETA_SUMMARY:
    case TSUIDS:
        uri.append(tsmeta_type);
        break;
    case UIDMETA:
        uri.append(uidmeta_type);
        break;
    case ANNOTATION:
        uri.append(annotation_type);
        break;
    }
    uri.append("/_search");

    // setup the query body
    HashMap<String, Object> body = new HashMap<String, Object>(3);
    body.put("size", query.getLimit());
    body.put("from", query.getStartIndex());

    HashMap<String, Object> qs = new HashMap<String, Object>(1);
    body.put("query", qs);
    HashMap<String, String> query_string = new HashMap<String, String>(1);
    query_string.put("query", query.getQuery());
    qs.put("query_string", query_string);

    final Request request = Request.Post(uri.toString());
    request.bodyByteArray(JSON.serializeToBytes(body));

    final Async async = Async.newInstance().use(threadpool);
    async.execute(request, new SearchCB(query, result));
    return result;
}

From source file:com.qwazr.search.index.IndexSingleClient.java

@Override
public AnalyzerDefinition setAnalyzer(String schema_name, String index_name, String analyzer_name,
        AnalyzerDefinition analyzer) {/*from   w w  w  .  ja va  2  s  . co  m*/
    UBuilder uriBuilder = new UBuilder("/indexes/", schema_name, "/", index_name, "/analyzers/", analyzer_name);
    Request request = Request.Post(uriBuilder.build());
    return commonServiceRequest(request, analyzer, null, AnalyzerDefinition.class, 200);
}

From source file:org.exist.xquery.RestBinariesTest.java

private HttpResponse postXquery(final String xquery) throws JAXBException, IOException {
    final Query query = new Query();
    query.setText(xquery);/*w  w w  . j a v  a2  s  .  c  om*/

    final JAXBContext jaxbContext = JAXBContext.newInstance("org.exist.http.jaxb");
    final Marshaller marshaller = jaxbContext.createMarshaller();

    final HttpResponse response;
    try (final FastByteArrayOutputStream baos = new FastByteArrayOutputStream()) {
        marshaller.marshal(query, baos);
        response = executor.execute(Request.Post(getRestUrl() + "/db/").bodyByteArray(baos.toByteArray(),
                ContentType.APPLICATION_XML)).returnResponse();
    }

    if (response.getStatusLine().getStatusCode() != SC_OK) {
        throw new IOException(
                "Unable to query, HTTP response code: " + response.getStatusLine().getStatusCode());
    }

    return response;
}