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, Charset charset) 

Source Link

Usage

From source file:se.vgregion.pubsub.push.impl.HttpUtil.java

public static HttpEntity createEntity(Document doc) {
    try {//w  ww. j  a va2  s.  c om
        return new StringEntity(doc.toXML(), "UTF-8");
    } catch (UnsupportedEncodingException shouldNeverHappen) {
        throw new RuntimeException(shouldNeverHappen);
    }
}

From source file:io.kahu.hawaii.util.call.http.SoapRequest.java

public SoapRequest(RequestDispatcher requestDispatcher, RequestContext<T> context, String url, String content,
        String soapAction, ResponseHandler<HttpResponse, T> responseHandler, CallLogger<T> logger) {

    super(requestDispatcher, context, responseHandler, new HttpPost(url), logger);

    HttpEntity httpEntity = new StringEntity(content, ContentType.create("text/xml", "UTF-8"));
    getHttpRequest().setHeader("Content-Type", "text/xml;charset=UTF-8");
    getHttpRequest().setHeader("SOAPAction", '"' + soapAction + '"');
    ((HttpPost) getHttpRequest()).setEntity(httpEntity);
}

From source file:com.vmware.photon.controller.clustermanager.clients.HttpClientTestUtil.java

@SuppressWarnings("unchecked")
public static CloseableHttpAsyncClient setupMocks(String serializedResponse, int responseCode)
        throws IOException {
    CloseableHttpAsyncClient asyncHttpClient = Mockito.mock(CloseableHttpAsyncClient.class);

    Mockito.doAnswer(new Answer<Object>() {
        @Override// w  w  w . ja v a  2  s  .co m
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return null;
        }
    }).when(asyncHttpClient).close();

    final HttpResponse httpResponse = Mockito.mock(HttpResponse.class);
    StatusLine statusLine = Mockito.mock(StatusLine.class);
    Mockito.when(httpResponse.getStatusLine()).thenReturn(statusLine);
    Mockito.when(statusLine.getStatusCode()).thenReturn(responseCode);
    Mockito.when(httpResponse.getEntity())
            .thenReturn(new StringEntity(serializedResponse, ContentType.APPLICATION_JSON));

    final Future<HttpResponse> httpResponseFuture = new Future<HttpResponse>() {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            return false;
        }

        @Override
        public boolean isCancelled() {
            return false;
        }

        @Override
        public boolean isDone() {
            return true;
        }

        @Override
        public HttpResponse get() throws InterruptedException, ExecutionException {
            return httpResponse;
        }

        @Override
        public HttpResponse get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return httpResponse;
        }
    };

    Mockito.when(
            asyncHttpClient.execute(Matchers.any(HttpUriRequest.class), Matchers.any(BasicHttpContext.class),
                    Matchers.any(org.apache.http.concurrent.FutureCallback.class)))
            .thenAnswer(new Answer<Object>() {
                @Override
                public Object answer(InvocationOnMock invocation) throws Throwable {
                    if (invocation.getArguments()[2] != null) {
                        ((org.apache.http.concurrent.FutureCallback<HttpResponse>) invocation.getArguments()[2])
                                .completed(httpResponse);
                    }
                    return httpResponseFuture;
                }
            });
    return asyncHttpClient;
}

From source file:org.apache.camel.itest.http.Http4EndpointTest.java

@BeforeClass
public static void setUp() throws Exception {
    localServer = new HttpTestServer(null, null);
    localServer.register("/", new HttpRequestHandler() {
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            response.setStatusCode(HttpStatus.SC_OK);
            response.setEntity(new StringEntity("OK", Consts.ISO_8859_1));
        }/*from  ww w  .  j  ava  2  s .c  o m*/
    });
    localServer.start();
}

From source file:org.arquillian.graphene.visual.testing.test.RestUtilsTest.java

@Test
public void testResponse() {
    String token = "test-word";
    CloseableHttpClient httpClient = RestUtils.getHTTPClient(conf.getJcrContextRootURL(), conf.getJcrUserName(),
            conf.getJcrPassword());//  ww  w  .j  a v  a  2  s.  com
    HttpPost postCreateWords = new HttpPost(
            conf.getManagerContextRootURL() + "graphene-visual-testing-webapp/rest/words");
    StringEntity wordEnity = new StringEntity("{\"value\": \"" + token + "\"}", ContentType.APPLICATION_JSON);
    postCreateWords.setHeader("Content-Type", "application/json");
    postCreateWords.setEntity(wordEnity);
    String response = RestUtils.executePost(postCreateWords, httpClient, token + " created",
            "FAILED TO CREATE: " + token);
}

From source file:org.jitsi.meet.test.util.JvbUtil.java

static private void triggerShutdown(HttpClient client, String jvbEndpoint, boolean force) throws IOException {
    String url = jvbEndpoint + "/colibri/shutdown";

    HttpPost post = new HttpPost(url);

    StringEntity requestEntity = new StringEntity(
            force ? "{ \"force-shutdown\": \"true\" }" : "{ \"graceful-shutdown\": \"true\" }",
            ContentType.APPLICATION_JSON);

    post.setEntity(requestEntity);/*from w  ww  .  ja  va2s  .  co  m*/

    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + post.getEntity());

    HttpResponse response = client.execute(post);

    int responseCode = response.getStatusLine().getStatusCode();
    if (200 != responseCode) {
        throw new RuntimeException(
                "Failed to trigger graceful shutdown on: " + jvbEndpoint + ", response code: " + responseCode);
    }
}

From source file:com.jubination.io.chatbot.backend.service.core.DashBotUpdater.java

public String sendAutomatedUpdate(DashBot dashbot, String type) {
    String responseText = "";
    try {/*from  w  ww  .  ja v  a  2 s  .co  m*/
        String url = "https://tracker.dashbot.io/track?platform=generic&v=0.8.2-rest&type=" + type
                + "&apiKey=bJt7U0oEG79HSUm4nJWUQTPm1nhjKu3gieZ83M0O";
        ObjectMapper mapper = new ObjectMapper();
        //Object to JSON in String
        String jsonString = mapper.writeValueAsString(dashbot);
        HttpClient httpClient = HttpClientBuilder.create().build();
        // System.out.println(jsonString+"STRING JSON TO DASH BOT");
        StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
        HttpPost postMethod = new HttpPost(url);
        postMethod.setEntity(requestEntity);
        HttpResponse response = httpClient.execute(postMethod);
        HttpEntity entity = response.getEntity();
        responseText = EntityUtils.toString(entity, "UTF-8");

    } catch (Exception ex) {
        Logger.getLogger(DashBotUpdater.class.getName()).log(Level.SEVERE, null, ex);
    }
    // System.out.println(responseText);
    return responseText;
}

From source file:com.anteam.demo.logback.appender.HttpAppender.java

@Override
protected void append(E event) {
    System.out.println(((LoggingEvent) event).getFormattedMessage());
    StringEntity stringEntity = new StringEntity(event.toString(), ContentType.create("text/plain", "UTF-8"));
    HttpPost post = new HttpPost(url);
    post.setEntity(stringEntity);/*w  ww.j av  a  2s.  c o m*/
    HttpResponse response = null;
    try {
        response = httpclient.execute(post);
    } catch (ClientProtocolException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    // Examine the response status
    System.out.println(response.getStatusLine());

    // Get hold of the response entity
    HttpEntity entity = response.getEntity();

    // If the response does not enclose an entity, there is no need
    // to worry about connection release
    if (entity != null) {
        InputStream instream = null;
        try {
            instream = entity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            // do something useful with the response
            System.out.println(reader.readLine());

        } catch (Exception ex) {
            post.abort();

        } finally {

            try {
                instream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

From source file:juzu.plugin.jackson.AbstractJacksonRequestTestCase.java

@Test
public void testRequest() throws Exception {
    HttpPost post = new HttpPost(applicationURL() + "/post");
    post.setEntity(new StringEntity("{\"foo\":\"bar\"}", ContentType.APPLICATION_JSON));
    HttpClient client = HttpClientBuilder.create().build();
    payload = null;/*from  ww  w. j a v  a2  s . com*/
    client.execute(post);
}

From source file:com.nominanuda.web.http.SerializeDeserializeTest.java

@Test
public void testRequest() throws IOException, HttpException {
    HttpPost req = new HttpPost(REQ_URI);
    req.addHeader("h1", "v1");
    req.setEntity(new StringEntity(PAYLOAD, ContentType.create("text/plain", "UTF-8")));
    byte[] serialized = HTTP.serialize(req);
    //System.err.println(new String(serialized, "UTF-8"));
    HttpPost m = (HttpPost) HTTP.deserialize(new ByteArrayInputStream(serialized));
    //System.err.println(new String(HTTP.serialize(m), "UTF-8"));
    assertEquals(REQ_URI, m.getRequestLine().getUri());
    assertEquals(PAYLOAD.getBytes(HttpProtocol.CS_UTF_8).length,
            ((ByteArrayEntity) m.getEntity()).getContentLength());
    assertEquals("v1", m.getFirstHeader("h1").getValue());
}