Example usage for org.apache.http.entity StringEntity StringEntity

List of usage examples for org.apache.http.entity StringEntity StringEntity

Introduction

In this page you can find the example usage for org.apache.http.entity StringEntity StringEntity.

Prototype

public StringEntity(String str) throws UnsupportedEncodingException 

Source Link

Usage

From source file:ch.mbae.pusher.transport.HttpClientPusherTransport.java

public PusherResponse fetch(URL url, String jsonData) throws PusherTransportException {
    PusherResponse response = new PusherResponse();
    try {/*from   w w w.j a va 2s . c o  m*/
        HttpPost post = new HttpPost(url.toURI());

        post.addHeader("Content-Type", "application/json");
        post.setEntity(new StringEntity(jsonData));
        // executr post request
        HttpResponse httpResponse = this.httpClient.execute(post);

        // get the content
        response.setContent(EntityUtils.toByteArray(httpResponse.getEntity()));
        // extract and set headers
        response.setHeaders(this.extractHeaders(httpResponse));
        // set http status
        response.setResponseCode(httpResponse.getStatusLine().getStatusCode());

    } catch (URISyntaxException ex) {
        throw new PusherTransportException("bad uri syntax", ex);
    } catch (ClientProtocolException ex) {
        throw new PusherTransportException("bad client protocol", ex);
    } catch (IOException ex) {
        throw new PusherTransportException("i/o failed", ex);
    }

    return response;
}

From source file:com.predic8.membrane.servlet.test.ForwardingTest.java

@Test
public void testReachable() throws ClientProtocolException, IOException {
    String secret = "secret452363763";
    HttpClient hc = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(getBaseURL());
    post.setEntity(new StringEntity(secret));
    HttpResponse res = hc.execute(post);
    assertEquals(200, res.getStatusLine().getStatusCode());

    AssertUtils.assertContains(secret, EntityUtils.toString(res.getEntity()));
}

From source file:com.intel.cosbench.controller.tasklet.AbstractHttpTasklet.java

private static HttpPost prepareRequest(String content, String url) {
    HttpPost POST = new HttpPost(url);
    try {/*w  ww  .j  a  v  a2s.  c  o  m*/
        if (StringUtils.isNotEmpty(content))
            POST.setEntity(new StringEntity(content));
    } catch (Exception e) {
        throw new UnexpectedException(e); // will not happen
    }
    if (content != null && content.length() > 0)
        if (!content.startsWith("<?xml"))
            LOGGER.debug("[ >> ] - {} -> {}", content, url);
        else
            LOGGER.debug("[ >> ] - [xml-content] -> {}", url);
    else
        LOGGER.debug("[ >> ] - [empty-body] -> {}", url);
    return POST; // HTTP request prepared
}

From source file:Yak_Hax.Yak_Hax_Mimerme.PostRequest.java

public static String PostBodyRequest(String URL, String JSONRaw, TreeMap<String, String> headers)
        throws IOException {

    HttpPost post = new HttpPost(URL);

    HttpClient httpclient = HttpClients.custom().build();
    post.setEntity(new StringEntity(JSONRaw));
    post.setHeader("Content-Type", "application/json; charset=utf-8");
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();

        post.setHeader(key, value);//from  w  w  w  .j a va 2 s .  com
    }
    HttpResponse response = httpclient.execute(post);

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }
    return result.toString();
}

From source file:de.e7o.caldav.caldav.Connection.java

public InputStream request(String extUri, String requestMethod, String bodyData, String[]... additionalHeaders)
        throws Exception {
    int i;/*from w  w w  .jav a2s . co  m*/

    // Pre
    HttpClient httpclient = new DefaultHttpClient();
    HttpAny ha = new HttpAny(base.baseUri + extUri);
    ha.setMethod(requestMethod);

    // Headers
    for (i = 0; i < additionalHeaders.length; i++) {
        ha.addHeader(additionalHeaders[i][0], additionalHeaders[i][1]);
    }

    // Body
    ha.setEntity(new StringEntity(bodyData));

    // Authentication
    URL url = new URL(base.baseUri);
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.authInfo.getUserName(),
            this.authInfo.getPassword());
    ((AbstractHttpClient) httpclient).getCredentialsProvider()
            .setCredentials(new AuthScope(url.getHost(), 80, null, "Basic"), credentials);

    // Send request
    HttpResponse httpresp = httpclient.execute(ha);

    // Remember state
    lastCode = httpresp.getStatusLine().getStatusCode();
    lastHeaders = httpresp.getAllHeaders();

    // Done - return InputStream
    HttpEntity httpent = httpresp.getEntity();
    return httpent.getContent();
}

From source file:com.github.restdriver.clientdriver.integration.BodyCaptureTest.java

@Test
public void canCaptureRequestBodyAsString() throws Exception {

    StringBodyCapture capture = new StringBodyCapture();

    clientDriver.addExpectation(onRequestTo("/foo").withMethod(Method.POST).capturingBodyIn(capture),
            giveEmptyResponse().withStatus(201));

    HttpClient client = new DefaultHttpClient();
    HttpPost correctPost = new HttpPost(clientDriver.getBaseUrl() + "/foo");
    correctPost.setEntity(new StringEntity("a string"));
    HttpResponse correctResponse = client.execute(correctPost);
    EntityUtils.consume(correctResponse.getEntity());

    assertThat(capture.getContent(), is("a string"));
}

From source file:com.jts.main.helper.Http.java

public static String getPost(String url, URLParameter param) {
    String retval = "";
    HttpClient httpClient = new DefaultHttpClient();
    try {/*from  w  ww .  j  a  v  a  2s.c o  m*/
        String prm = param.toString();
        HttpPost request = new HttpPost(My.base_url + url);
        StringEntity params = new StringEntity(prm);
        request.addHeader("content-type", "application/x-www-form-urlencoded");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);
        // handle response here...
        retval = org.apache.http.util.EntityUtils.toString(response.getEntity());
        org.apache.http.util.EntityUtils.consume(response.getEntity());
    } catch (IOException | ParseException ex) {
        errMsg = ex.getMessage();
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return retval;
}

From source file:com.github.restdriver.clientdriver.integration.BodyMatchersTest.java

@Test
public void canUseStringMatcherWhenMatchingRequestBody() throws Exception {

    clientDriver.addExpectation(/*from   w  w  w  .java  2 s.  c o m*/
            onRequestTo("/foo").withMethod(Method.POST).withBody(containsString("str"), "text/plain"),
            giveEmptyResponse().withStatus(201));

    clientDriver.addExpectation(
            onRequestTo("/foo").withMethod(Method.POST).withBody(not(containsString("str")), "text/plain"),
            giveEmptyResponse().withStatus(202));

    HttpClient client = new DefaultHttpClient();

    HttpPost correctPost = new HttpPost(clientDriver.getBaseUrl() + "/foo");
    correctPost.setEntity(new StringEntity("a string containing my substring of 'str'"));

    HttpResponse correctResponse = client.execute(correctPost);
    EntityUtils.consume(correctResponse.getEntity());

    assertThat(correctResponse.getStatusLine().getStatusCode(), is(201));

    HttpPost incorrectPost = new HttpPost(clientDriver.getBaseUrl() + "/foo");
    incorrectPost.setEntity(new StringEntity("something containing my subst... WAIT, no, it doesn't"));

    HttpResponse incorrectResponse = client.execute(incorrectPost);
    EntityUtils.consume(incorrectResponse.getEntity());

    assertThat(incorrectResponse.getStatusLine().getStatusCode(), is(202));

}

From source file:com.gamethrive.GameThriveRestClient.java

static void post(final Context context, final String url, JSONObject jsonBody,
        final ResponseHandlerInterface responseHandler) throws UnsupportedEncodingException {
    final StringEntity entity = new StringEntity(jsonBody.toString());

    new Thread(new Runnable() {
        public void run() {
            clientSync.post(context, BASE_URL + url, entity, "application/json", responseHandler);
        }/*from w  ww  .  j  a  va 2  s  .c o  m*/
    }).start();
}

From source file:io.github.thred.climatetray.mnet.request.AbstractMNetRequest.java

@Override
public final void execute(URL url, String... additionalProxyExcludes) throws MNetRequestException {
    try {//from ww  w .  j a  v  a2s. com
        String content = buildRequest();
        StringEntity body = new StringEntity(content);
        CloseableHttpClient client = ClimateTray.PREFERENCES.getProxySettings()
                .createHttpClient(additionalProxyExcludes);
        HttpPost post = new HttpPost(url.toURI());

        post.setHeader("content-type", "text/xml");
        post.setEntity(body);

        LOG.debug("Sending request to \"%s\". The request is:\n%s", url.toExternalForm(), content);

        CloseableHttpResponse response;

        try {
            response = client.execute(post);
        } catch (IOException e) {
            throw new MNetRequestException("Failed to send request to \"%s\".", e, url.toExternalForm())
                    .hint(Message.error(
                            "Could not contact the centralized controller.\n\nThis usually indicates, that the value of the field \"Controller Address\" is wrong. "
                                    + "If you are sure, that the value is correct, there may be a firewall or a proxy in the way. "
                                    + "Try to call the URL \"%s\" in a browser.",
                            url.toExternalForm()));
        }

        try {
            int status = response.getStatusLine().getStatusCode();

            if ((status >= 200) && (status < 300)) {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    try {
                        InputStream in = entity.getContent();

                        try {
                            if (LOG.isDebugEnabled()) {
                                byte[] bytes = Utils.toByteArray(in);

                                LOG.debug("Reading response from \"%s\". The response is:\n%s",
                                        url.toExternalForm(), new String(bytes, "UTF-8"));

                                in = new ByteArrayInputStream(bytes);
                            }

                            parseResponse(in);
                        } finally {
                            in.close();
                        }
                    } catch (MNetRequestException e) {
                        throw e;
                    } catch (Exception e) {
                        throw new MNetRequestException("Failed to parse response from \"%s\".", e,
                                url.toExternalForm())
                                        .hint(Message.error("The parsing of the response failed.\n\n"
                                                + "The request hit a server, but it may be the wrong one (the log may contain a more detailed description). "
                                                + "Check the contents of the field \"Controller Address\" or try to call the URL \"%s\" in a browser.",
                                                url.toExternalForm()));
                    }
                }
            } else {
                throw new MNetRequestException("Request to \"%s\" failed with error %d.", url.toExternalForm(),
                        status).hint(
                                Message.error("The request failed with error %d.\n\n"
                                        + "The request hit a server, but it may be the wrong one. "
                                        + "Check the contents of the field \"Controller Address\" again or try to call the URL \"%s\" in a browser.",
                                        status, url.toExternalForm()));
            }
        } finally {
            response.close();
        }
    } catch (MNetRequestException e) {
        throw e;
    } catch (Exception e) {
        throw new MNetRequestException("Sending an request to \"%s\" failed with an unhandled error: %s.", e,
                url.toExternalForm(), e.toString())
                        .hint(Message.error(
                                "The request failed for some unknown reason.\n\nYou can check the log for the detailed exception."));
    }
}