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:MinimalServerTest.java

License:asdf

public void testStartOfSession() throws Exception {
    //Create client
    HttpClient client = new DefaultHttpClient();
    HttpPost mockRequest = new HttpPost("http://localhost:5555/login");
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    mockRequest.setHeader("Content-type", "application/x-www-form-urlencoded");

    //Add parameters
    List<NameValuePair> urlParameters = new ArrayList<>();
    urlParameters.add(new BasicNameValuePair("email", "test"));
    urlParameters.add(new BasicNameValuePair("deviceUID", "BD655C43-3A73-4DFB-AA1F-074A4F0B0DCE"));
    mockRequest.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8"));
    //Execute the request
    HttpResponse mockResponse = client.execute(mockRequest, httpContext);

    //Test if normal login is successful
    BufferedReader rd = new BufferedReader(new InputStreamReader(mockResponse.getEntity().getContent()));
    rd.close();//from ww  w .  j av a 2  s .  c  o  m
    URL newURL = new URL("http://127.0.0.1:5555/start");
    final Request request = Request.Post(newURL.toURI());
    ExecutorService executor = Executors.newFixedThreadPool(1);
    Async async = Async.newInstance().use(executor);
    Future<Content> future = async.execute(request, new FutureCallback<Content>() {
        @Override
        public void failed(final Exception e) {
            e.printStackTrace();
        }

        @Override
        public void completed(final Content content) {
            System.out.println("Done");
        }

        @Override
        public void cancelled() {

        }
    });

    server.startSession();
    String asyncResponse = future.get().asString();
    JSONObject jsonTest = new JSONObject();
    //                "status": "1", //0 if the app should keep waiting, 1 for success, 2 if the votong session has fininshed
    //              "sessionType": "normal", //alternatively Yes/No or winner
    //              "rangeBottom": "0",
    //              "rangeTop": "15",
    //              "description": "image discription here",
    //              "comments": "True",  //True if comments are allowed, False if not
    //              "imgPath": "path/to/image.jpg" //the path where the image resides on the server
    jsonTest.put("status", "1");
    jsonTest.put("sessionType", "normal");
    jsonTest.put("rangeBottom", 0);
    jsonTest.put("rangeTop", 10);
    jsonTest.put("description", "helo");
    jsonTest.put("comments", "true");
    jsonTest.put("imgPath", "temp/1.jpg");
    assertEquals("Testing if login was correctly failed due to incorrect username", jsonTest.toString(),
            asyncResponse);
}

From source file:org.kie.smoke.wb.util.RestUtil.java

public static <T> T post(URL deploymentUrl, String relativeUrl, String mediaType, int status, String user,
        String password, double timeoutInSecs, Class<T>... responseTypes) {

    String uriStr = createBaseUriString(deploymentUrl, relativeUrl);

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

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

    Response resp = null;/*from w  ww.ja  v  a  2 s  . co  m*/
    long before = 0, after = 0;
    try {
        logOp("POST", uriStr);
        before = System.currentTimeMillis();
        resp = request.execute();
        after = System.currentTimeMillis();
    } catch (Exception e) {
        logAndFail("[GET] " + uriStr, e);
    }

    long duration = after - before;
    assertTrue("Timeout exceeded " + timeoutInSecs + " secs: " + ((double) duration / 1000d) + " secs",
            duration < timeoutInSecs * 1000);

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

    // never happens
    return null;
}

From source file:org.kie.remote.tests.base.RestUtil.java

public static <T> T post(URL deploymentUrl, String relativeUrl, String mediaType, int status, String user,
        String password, double timeoutInSecs, Class<T>... responseTypes) {

    String uriStr = createBaseUriString(deploymentUrl, relativeUrl);

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

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

    Response resp = null;//from   w w  w .  ja  v a2 s  .c om
    long before = 0, after = 0;
    try {
        logOp("POST", uriStr);
        before = System.currentTimeMillis();
        resp = request.execute();
        after = System.currentTimeMillis();
    } catch (Exception e) {
        failAndLog("[GET] " + uriStr, e);
    }

    long duration = after - before;
    assertTrue("Timeout exceeded " + timeoutInSecs + " secs: " + ((double) duration / 1000d) + " secs",
            duration < timeoutInSecs * 1000);

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

    // never happens
    return null;
}

From source file:gate.tagger.tagme.TaggerTagMeWS.java

protected String retrieveServerResponse(String text) {
    Request req = Request.Post(getTagMeServiceUrl().toString());

    req.addHeader("Content-Type", "application/x-www-form-urlencoded");
    req.bodyForm(/*from www . ja va2 s. co m*/
            Form.form().add("text", text).add("gcube-token", getApiKey()).add("lang", getLanguageCode())
                    .add("tweet", getIsTweet().toString()).add("include_abstract", "false")
                    .add("include_categories", "false").add("include_all_spots", "false")
                    .add("long_text", getLongText().toString()).add("epsilon", getEpsilon().toString()).build(),
            Consts.UTF_8);
    logger.debug("Request is " + req);
    Response res = null;
    try {
        res = req.execute();
    } catch (Exception ex) {
        throw new GateRuntimeException("Problem executing HTTP request: " + req, ex);
    }
    Content cont = null;
    try {
        cont = res.returnContent();
    } catch (Exception ex) {
        throw new GateRuntimeException("Problem getting HTTP response content: " + res, ex);
    }
    String ret = cont.asString();
    logger.debug("TagMe server response " + ret);
    return ret;
}

From source file:eu.trentorise.opendata.jackan.ckan.CkanClient.java

/**
 *
 * @param <T>/*  w w w. j a  v a  2 s .com*/
 * @param responseType a descendant of CkanResponse
 * @param path something like 1/api/3/action/package_create
 * @param body the body of the POST
 * @param the content type, i.e.
 * @param params list of key, value parameters. They must be not be url
 * encoded. i.e. "id","laghi-monitorati-trento"
 * @throws JackanException on error
 */
<T extends CkanResponse> T postHttp(Class<T> responseType, String path, String body, ContentType contentType,
        Object... params) {
    checkNotNull(responseType);
    checkNotNull(path);
    checkNotNull(body);
    checkNotNull(contentType);

    String fullUrl = calcFullUrl(path, params);

    try {

        logger.log(Level.FINE, "posting to url {0}", fullUrl);
        Request request = Request.Post(fullUrl);
        if (proxy != null) {
            request.viaProxy(proxy);
        }
        Response response = request.bodyString(body, contentType).addHeader("Authorization", ckanToken)
                .execute();

        Content out = response.returnContent();
        String json = out.asString();

        T dr = getObjectMapper().readValue(json, responseType);
        if (!dr.success) {
            // monkey patching error type
            throw new JackanException("posting to catalog " + catalogURL + " was not successful. Reason: "
                    + CkanError.read(getObjectMapper().readTree(json).get("error").asText()));
        }
        return dr;
    } catch (Exception ex) {
        throw new JackanException("Error while performing a POST! Request url is:" + fullUrl, ex);
    }

}

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

/**
 * creates a new comment with a given library id and document id
 * // w ww  .  ja va  2s .c  om
 * @param bearer
 *            the accesstoken used to make the request
 * @param pid
 *            the document id
 * @param uid
 *            the library id
 * @param body
 *            the body of the comment
 * @param nonce
 *            the nonce code
 * @param response
 *            the http response that the results are sent to
 */
public void createComment(String bearer, String pid, String uid, String body, String nonce,
        HttpServletResponse response) {
    String apiUrl = getApiUrl() + "/library/" + uid + "/document/" + pid + "/feed";

    logger.info(apiUrl);

    try {
        JSONObject obj = new JSONObject(body);

        String comment = generateComment(obj.getString("comment"));

        // Generate the
        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(comment.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();

        // Process the Status Codes
        if (code == HttpStatus.SC_FORBIDDEN) {
            // Session is no longer valid or access token is expired
            response.setStatus(HttpStatus.SC_FORBIDDEN);
        } else if (code == HttpStatus.SC_UNAUTHORIZED) {
            // User is not authorized
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        } else if (code == HttpStatus.SC_CREATED) {
            // Default to 201
            response.setStatus(HttpStatus.SC_OK);

            InputStream in = hr.getEntity().getContent();

            String jsonString = org.apache.wink.json4j.utils.XML.toJson(in);

            JSONObject base = new JSONObject(jsonString);
            JSONObject entry = base.getJSONObject("entry");
            JSONObject author = entry.getJSONObject("author");

            String name = author.getString("name");
            String userid = author.getString("userid");
            String date = entry.getString("modified");
            String content = entry.getString("content");
            String cid = entry.getString("uuid");

            // Build the JSON object
            JSONObject commentJSON = new JSONObject();
            commentJSON.put("uid", userid);
            commentJSON.put("author", name);
            commentJSON.put("date", date);
            commentJSON.put("content", content);
            commentJSON.put("cid", cid);

            // Flush the Object to the Stream with content type
            response.setHeader("Content-Type", "application/json");

            PrintWriter out = response.getWriter();
            out.write(commentJSON.toString());
            out.flush();
            out.close();

        }

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

From source file:de.elomagic.maven.http.HTTPMojo.java

private Request createRequestMethod() throws Exception {
    switch (method) {
    case DELETE://www . j ava  2  s.c  o  m
        return Request.Delete(url.toURI());
    case GET:
        return Request.Get(url.toURI());
    case HEAD:
        return Request.Head(url.toURI());
    case POST:
        return Request.Post(url.toURI());
    case PUT:
        return Request.Put(url.toURI());
    }

    throw new Exception("Unsupported HTTP method \"" + method + "\".");
}

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

@Override
public Response postMappedDocument(String schema_name, String index_name, Map<String, Object> document) {
    try {//from   w  ww  . jav  a2  s  . co m
        UBuilder uriBuilder = new UBuilder("/indexes/", schema_name, "/", index_name, "/doc");
        Request request = Request.Post(uriBuilder.build());
        HttpResponse response = execute(request, document, null);
        HttpUtils.checkStatusCodes(response, 200);
        return Response.status(response.getStatusLine().getStatusCode()).build();
    } catch (HttpResponseEntityException e) {
        throw e.getWebApplicationException();
    } catch (IOException e) {
        throw new WebApplicationException(e.getMessage(), e, Status.INTERNAL_SERVER_ERROR);
    }
}

From source file:me.vertretungsplan.parser.BaseParser.java

protected String httpPost(String url, String encoding, List<NameValuePair> formParams,
        Map<String, String> headers) throws IOException, CredentialInvalidException {
    Request request = Request.Post(url).bodyForm(formParams).connectTimeout(15000).socketTimeout(15000);
    if (headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            request.addHeader(entry.getKey(), entry.getValue());
        }/*from www.  j  av  a 2s. c o  m*/
    }
    return executeRequest(encoding, request);
}

From source file:com.twosigma.beaker.NamespaceClient.java

private String runStringRequest(String urlfragment, Form postdata) throws ClientProtocolException, IOException {
    String reply = Request.Post(ctrlUrlBase + urlfragment).addHeader("Authorization", auth)
            .bodyForm(postdata.build()).execute().returnContent().asString();
    return objectMapper.get().readValue(reply, StringObject.class).getText();
}