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, int status, String user, String password,
        Class[] classes, Object entity, Class<T>... responseTypes) {

    String uriStr = createBaseUriString(deploymentUrl, relativeUrl);

    String mediaType = MediaType.APPLICATION_XML;
    ResponseHandler<T> rh = createResponseHandler(mediaType, status, responseTypes);
    XmlResponseHandler xrh = (XmlResponseHandler) rh;

    xrh.addExtraJaxbClasses(classes);//from   w ww.j  a  va2  s . c om
    String entityStr = xrh.serialize(entity);

    HttpEntity bodyEntity = null;
    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:com.qwazr.search.index.IndexSingleClient.java

@Override
public FieldDefinition setField(String schema_name, String index_name, String field_name,
        FieldDefinition field) {//from w ww .j  a v  a2  s  . c  om
    UBuilder uriBuilder = new UBuilder("/indexes/", schema_name, "/", index_name, "/fields/", field_name);
    Request request = Request.Post(uriBuilder.build());
    return commonServiceRequest(request, field, null, FieldDefinition.class, 200);
}

From source file:com.baifendian.swordfish.common.storm.StormRestUtil.java

/**
 * ??/*w  w  w . j a v  a  2  s  . c  om*/
 */
public static void topologyActivate(String topologyId) throws Exception {
    String res = Request.Post(getTopologyActivateUrl(topologyId)).execute().returnContent().toString();

    TopologyOperationDto topologyOperation = JsonUtil.parseObject(res, TopologyOperationDto.class);

    if (topologyOperation == null) {
        throw new Exception("Activate not result return!");
    }

    if (!StringUtils.equalsIgnoreCase(topologyOperation.getStatus(), "success")) {
        String msg = MessageFormat.format("Activate status not equal success: {0}",
                topologyOperation.getStatus());
        throw new Exception(msg);
    }
}

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

@Test
public void nonBlockingFlowRef() throws Exception {
    Response response = Request
            .Post(String.format("http://localhost:%s/%s", port.getNumber(), "nonBlockingFlowRefBasic"))
            .connectTimeout(RECEIVE_TIMEOUT).bodyString(TEST_MESSAGE, ContentType.TEXT_PLAIN).execute();
    HttpResponse httpResponse = response.returnResponse();
    assertThat(httpResponse.getStatusLine().getStatusCode(), is(200));
    assertThat(IOUtils.toString(httpResponse.getEntity().getContent()), is(TEST_MESSAGE));

    SensingNullRequestResponseMessageProcessor flow1RequestResponseProcessor = muleContext.getRegistry()
            .lookupObject(FLOW1_SENSING_PROCESSOR_NAME);
    SensingNullRequestResponseMessageProcessor flow2RequestResponseProcessor = muleContext.getRegistry()
            .lookupObject(FLOW2_SENSING_PROCESSOR_NAME);
    assertThat(flow1RequestResponseProcessor.requestThread,
            not(equalTo(flow1RequestResponseProcessor.responseThread)));
    assertThat(flow2RequestResponseProcessor.requestThread,
            not(equalTo(flow2RequestResponseProcessor.responseThread)));
}

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

/**
 * uploads a file to the IBM Connections Cloud using the Files Service
 * //from  w w w  .  jav a 2 s .c  o m
 * @param bearer token
 * @param nonce 
 * @param request
 * @param response
 */
public void uploadFile(String bearer, String nonce, HttpServletRequest request, HttpServletResponse response) {

    // Extracts from the Request Parameters
    String visibility = request.getParameter("visibility");
    String title = request.getParameter("title");
    String share = request.getParameter("share");
    String tagsUnsplit = request.getParameter("q");

    // Check for the Required Parameters
    if (visibility == null || title == null || title.isEmpty() || visibility.isEmpty()) {
        response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);

    } else {

        /*
         * Builds the URL Parameters 
         */
        StringBuilder builder = new StringBuilder();
        builder.append("visibility=" + visibility + "&");
        builder.append("title=" + title + "&");

        // The Share parameters for the URL
        if (share != null && !share.isEmpty()) {
            builder.append("shared=true&");
            builder.append("shareWith=" + share + "&");
        }

        if (visibility.compareTo("private") == 0 && share == null) {
            builder.append("shared=false&");
        }

        // Splits the TagString into Indvidual Tags
        // - Technically this API is limited to 3 tags at most. 
        String[] tags = tagsUnsplit.split(",");
        for (String tag : tags) {
            logger.info("Tag-> " + tag);
            builder.append("tag=" + tag + "&");
        }

        // Build the apiURL
        String apiUrl = getApiUrl() + "/myuserlibrary/feed?" + builder.toString();

        //API Url
        logger.info(apiUrl);

        // Add the Headers
        String length = request.getHeader("X-Content-Length");
        String contentType = request.getHeader("Content-Type");
        String fileext = contentType.split("/")[1].split(";")[0];
        String slug = title + "." + fileext;

        Request post = Request.Post(apiUrl);
        post.addHeader("Authorization", "Bearer " + bearer);
        post.addHeader("X-Update-Nonce", nonce);
        post.addHeader("Slug", slug);
        post.addHeader("Content-Type", contentType);

        logger.info("Authorization: Bearer " + bearer);
        logger.info("X-Update-Nonce: " + nonce);
        logger.info("Slug: " + slug);
        logger.info("Content-Type: " + contentType);

        try {
            //
            InputStream in = request.getInputStream();
            Base64InputStream bis = new Base64InputStream(in);

            long len = Long.parseLong(length);
            InputStreamEntity entity = new InputStreamEntity(bis, len);

            post.body(entity);

            post.removeHeaders("Cookie");

            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 is " + 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);
            }

            // Duplicate Item
            else if (code == HttpStatus.SC_CONFLICT) {
                response.setStatus(HttpStatus.SC_CONFLICT);
            }

            // Checks if Created
            else if (code == HttpStatus.SC_CREATED) {
                response.setStatus(HttpStatus.SC_OK);
                /**
                 * Do Extra Processing Here to process the body
                 */
                InputStream inRes = hr.getEntity().getContent();

                // Converts XML to JSON String
                String jsonString = org.apache.wink.json4j.utils.XML.toJson(inRes);
                JSONObject obj = new JSONObject(jsonString);

                response.setContentType("application/json");
                PrintWriter writer = response.getWriter();
                writer.append(obj.toString());
                writer.close();

            } else {
                // Catch All
                response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                InputStream inRes = hr.getEntity().getContent();
                String out = IOUtils.toString(inRes);
                logger.info("Content: " + out);
                logger.info("Content Type of Response: " + response.getContentType());

                Collection<String> coll = response.getHeaderNames();
                Iterator<String> iter = coll.iterator();

                while (iter.hasNext()) {
                    String header = iter.next();
                    logger.info(header + " " + response.getHeader(header));
                }

            }

        } 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();
        } catch (SAXException e) {
            response.setHeader("X-Application-Error", e.getClass().getName());
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            logger.severe("SAXException " + e.toString());
        } catch (JSONException e) {
            response.setHeader("X-Application-Error", e.getClass().getName());
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);

            logger.severe("JSONException " + e.toString());
        }
    }
}

From source file:org.n52.youngs.test.SpatialSearchIT.java

@Test
public void spatialQueryEnvelopeSearch() throws Exception {
    String endpoint = "http://localhost:9200/" + mapping.getIndex() + "/" + mapping.getType()
            + "/_search?pretty";

    String bboxCoveringTwoRecordsQuery = "{" + "    \"query\":{" + "        \"filtered\":{"
            + "            \"query\":{" + "                \"match_all\":{" + "                }"
            + "            }," + "            \"filter\":{" + "                \"geo_shape\":{"
            + "                    \"location\":{" + "                        \"shape\":{"
            + "                            \"type\":\"envelope\","
            + "                            \"coordinates\":[" + "                                ["
            + "                                    52.0," + "                                    -5.0"
            + "                                ]," + "                                ["
            + "                                    40.0," + "                                    6.5"
            + "                                ]" + "                            ]"
            + "                        }" + "                    }" + "                }" + "            }"
            + "        }" + "    }" + "}";

    String searchWithEnvelopeResponse = Request.Post(endpoint)
            .bodyString(bboxCoveringTwoRecordsQuery, ContentType.APPLICATION_JSON).execute().returnContent()
            .asString();/*from   w  w  w  . java 2  s  . c  o  m*/
    assertThat("correct number of records found", searchWithEnvelopeResponse, hasJsonPath("hits.total", is(2)));
    assertThat("ids are contained", searchWithEnvelopeResponse,
            allOf(not(containsString("urn:uuid:1ef30a8b-876d-4828-9246-c37ab4510bbd")),
                    containsString("urn:uuid:9a669547-b69b-469f-a11f-2d875366bbdc"),
                    containsString("urn:uuid:94bc9c83-97f6-4b40-9eb8-a8e8787a5c63")));
}

From source file:be.fedict.dcat.datagovbe.Drupal.java

/**
 * Prepare a POST or PUT action.//from w ww. ja va2 s  .  com
 * 
 * @param method POST or PUT
 * @param relpath relative path
 * @return 
 */
private Request prepare(String method, String relpath) {
    String u = this.url.toString() + relpath;

    Request r = method.equals(Drupal.POST) ? Request.Post(u) : Request.Put(u);

    r.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType()).setHeader(Drupal.X_TOKEN,
            token);

    if (proxy != null) {
        r.viaProxy(proxy);
    }
    return r;
}

From source file:eu.esdihumboldt.hale.io.geoserver.rest.AbstractResourceManager.java

/**
 * @see eu.esdihumboldt.hale.io.geoserver.rest.ResourceManager#create(java.util.Map)
 *///w  w w.ja  v  a  2  s  . co  m
@Override
public URL create(Map<String, String> parameters) {
    checkResourceSet();

    try {
        URI requestUri = buildRequestUri(getResourceListURL(), parameters);

        ByteArrayEntity entity = new ByteArrayEntity(resource.asByteArray());
        entity.setContentType(resource.contentType().getMimeType());

        return executor.execute(Request.Post(requestUri).body(entity))
                .handleResponse(new ResponseHandler<URL>() {

                    /**
                     * @see org.apache.http.client.ResponseHandler#handleResponse(org.apache.http.HttpResponse)
                     */
                    @Override
                    public URL handleResponse(HttpResponse response)
                            throws ClientProtocolException, IOException {
                        StatusLine statusLine = response.getStatusLine();
                        if (statusLine.getStatusCode() >= 300) {
                            throw new HttpResponseException(statusLine.getStatusCode(),
                                    statusLine.getReasonPhrase());
                        }
                        if (statusLine.getStatusCode() == 201) {
                            Header locationHeader = response.getFirstHeader("Location");
                            if (locationHeader != null) {
                                return new URL(locationHeader.getValue());
                            }
                        }
                        return null;
                    }
                });
    } catch (Exception e) {
        throw new ResourceException(e);
    }
}

From source file:de.elomagic.carafile.client.CaraFileClient.java

/**
 * Uploads data via an {@link InputStream} (Single chunk upload).
 * <p/>//from   w ww  . j  ava 2 s .co m
 * Single chunk upload means that the complete file will be upload in one step.
 *
 * @param in The input stream. It's not recommended to use a buffered stream.
 * @param filename Name of the file
 * @param contentLength Length of the content in bytes
 * @return Returns the {@link MetaData} of the uploaded stream
 * @throws IOException Thrown when unable to call REST services
 * @see CaraFileClient#uploadFile(java.net.URI, java.nio.file.Path, java.lang.String)
 */
public MetaData uploadFile(final InputStream in, final String filename, final long contentLength)
        throws IOException {
    if (registryURI == null) {
        throw new IllegalArgumentException("Parameter 'registryURI' must not be null!");
    }

    if (in == null) {
        throw new IllegalArgumentException("Parameter 'in' must not be null!");
    }

    URI peerURI = peerSelector.getURI(downloadPeerSet(), -1);

    if (peerURI == null) {
        throw new IOException("No peer for upload available");
    }

    URI uri = CaraFileUtils.buildURI(peerURI, "peer", "seedFile", filename);

    MessageDigest messageDigest = DigestUtils.getSha1Digest();

    try (BufferedInputStream bis = new BufferedInputStream(in);
            DigestInputStream dis = new DigestInputStream(bis, messageDigest)) {
        HttpResponse response = executeRequest(
                Request.Post(uri).bodyStream(dis, ContentType.APPLICATION_OCTET_STREAM)).returnResponse();

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            throw new HttpResponseException(statusCode,
                    "Unable to upload file: " + response.getStatusLine().getReasonPhrase());
        }

        MetaData md = getMetaDataFromResponse(response);

        if (!Hex.encodeHexString(messageDigest.digest()).equals(md.getId())) {
            throw new IOException("Peer response invalid SHA1 of file");
        }

        return md;
    }
}