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:es.logongas.iothome.agent.http.Http.java

public Object post(URL url, Object data) {
    try {//from www  .jav a  2 s . c om

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(url.toURI());

        StringEntity input = new StringEntity(objectMapper.writeValueAsString(data));
        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);
        String output = inputStreamToString(response.getEntity().getContent());

        if (response.getStatusLine().getStatusCode() != 201) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + "\n" + output);
        }

        httpClient.getConnectionManager().shutdown();

        return objectMapper.readValue(output, data.getClass());

    } catch (Exception ex) {

        throw new RuntimeException(ex);

    }
}

From source file:com.android.net.volley.toolbox.BasicNetworkTest.java

public void testHeadersAndPostParams() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK");
    fakeResponse.setEntity(new StringEntity("foobar"));
    mockHttpStack.setResponseToReturn(fakeResponse);
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = new Request<String>(Request.Method.GET, "http://foo", null) {

        @Override/*from  w w  w .  j  av  a 2s.  c  o m*/
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            return null;
        }

        @Override
        protected void deliverResponse(String response) {
        }

        @Override
        public Map<String, String> getHeaders() {
            Map<String, String> result = new HashMap<String, String>();
            result.put("requestheader", "foo");
            return result;
        }

        @Override
        public Map<String, String> getParams() {
            Map<String, String> result = new HashMap<String, String>();
            result.put("requestpost", "foo");
            return result;
        }
    };
    httpNetwork.performRequest(request);
    assertEquals("foo", mockHttpStack.getLastHeaders().get("requestheader"));
    assertEquals("requestpost=foo&", new String(mockHttpStack.getLastPostBody()));
}

From source file:org.terracotta.management.cli.rest.PostCommand.java

private void doPost(Context context) throws IOException, CommandInvocationException {

    HttpClient httpclient = HttpServices.getHttpClient();
    HttpPost httpPost = new HttpPost(context.getUrl());

    if (context.getData() != null) {
        httpPost.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded"));
        httpPost.setEntity(new StringEntity(context.getData()));
    }//from  w w w  .  j  av a 2 s .  co m
    HttpResponse response = httpclient.execute(httpPost);
    processEntity(response.getEntity(), response.getFirstHeader("Content-Type"), context);

}

From source file:com.yahoo.wiki.webservice.application.WikiMain.java

/**
 * Makes the dimensions passthrough.//from w w w .ja  v  a2s .co m
 * <p>
 * This method sends a lastUpdated date to each dimension in the dimension cache, allowing the health checks
 * to pass without having to set up a proper dimension loader. For each dimension, d, the following query is
 * sent to the /v1/cache/dimensions/d endpoint:
 * {
 *     "name": "d",
 *     "lastUpdated": "2016-01-01"
 * }
 *
 * @param port  The port through which we access the webservice
 *
 * @throws IOException If something goes terribly wrong when building the JSON or sending it
 */
private static void markDimensionCacheHealthy(int port) throws IOException {
    for (DimensionConfig dimensionConfig : new WikiDimensions().getAllDimensionConfigurations()) {
        String dimension = dimensionConfig.getApiName();
        HttpPost post = new HttpPost("http://localhost:" + port + "/v1/cache/dimensions/" + dimension);
        post.setHeader("Content-type", "application/json");
        post.setEntity(new StringEntity(
                String.format("{\n \"name\":\"%s\",\n \"lastUpdated\":\"2016-01-01\"\n}", dimension)));
        CloseableHttpClient client = HttpClientBuilder.create().build();
        CloseableHttpResponse response = client.execute(post);
        LOG.debug("Mark Dimension Cache Updated Response: ", response);
    }
}

From source file:com.psbk.modulperwalian.Controller.ControllerLogin.java

public JSONObject getDataLogin() {
    JSONObject obj = null;//from   ww  w.j  a  v a 2s  .c o  m
    HttpClient httpClient = HttpClientBuilder.create().build();
    String status = null;
    try {
        String url = getIp() + "login";
        HttpPost request = new HttpPost(url);
        StringEntity params = new StringEntity("{request:{\"username\":\"" + getUsername() + "\","
                + "\"password\":\"" + getPassword() + "\" } }");
        request.addHeader("content-type", "application/json");
        request.setEntity(params);

        HttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();
        status = EntityUtils.toString(entity, "UTF-8");
        JSONObject result;
        obj = new JSONObject(status);

    } catch (Exception ex) {
        System.out.println("Error karena : " + ex.getMessage());
    }

    return obj;
}

From source file:tech.beshu.ror.integration.IndicesReverseWildcardTests.java

private static void insertDoc(String docName, RestClient restClient) {
    if (adminClient == null) {
        adminClient = restClient;/*from   w w  w  .  ja  v a2  s .  c om*/
    }

    try {
        HttpPut request = new HttpPut(restClient.from("/logstash-" + docName + "/documents/doc-" + docName));
        request.setHeader("refresh", "true");
        request.setHeader("timeout", "50s");
        request.setHeader("Content-Type", "application/json");
        request.setEntity(new StringEntity("{\"title\": \"" + docName + "\"}"));
        System.out.println(body(restClient.execute(request)));

    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException("Test problem", e);
    }

    // Polling phase.. #TODO is there a better way?
    try {
        HttpResponse response;
        do {
            Thread.sleep(200);
            HttpHead request = new HttpHead(
                    restClient.from("/logstash-" + docName + "/documents/doc-" + docName));
            response = restClient.execute(request);
            System.out.println(
                    "polling for " + docName + ".. result: " + response.getStatusLine().getReasonPhrase());
        } while (response.getStatusLine().getStatusCode() != 200);
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException("Cannot configure test case", e);
    }
}

From source file:com.android.sensorbergVolley.toolbox.BasicNetworkTest.java

@Test
public void headersAndPostParams() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK");
    fakeResponse.setEntity(new StringEntity("foobar"));
    mockHttpStack.setResponseToReturn(fakeResponse);
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = new Request<String>(Request.Method.GET, "http://foo", null) {

        @Override/*from   w ww. j  ava  2 s .co  m*/
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            return null;
        }

        @Override
        protected void deliverResponse(String response) {
        }

        @Override
        public Map<String, String> getHeaders() {
            Map<String, String> result = new HashMap<String, String>();
            result.put("requestheader", "foo");
            return result;
        }

        @Override
        public Map<String, String> getParams() {
            Map<String, String> result = new HashMap<String, String>();
            result.put("requestpost", "foo");
            return result;
        }
    };
    httpNetwork.performRequest(request);
    assertEquals("foo", mockHttpStack.getLastHeaders().get("requestheader"));
    assertEquals("requestpost=foo&", new String(mockHttpStack.getLastPostBody()));
}

From source file:ca.ualberta.cmput301w13t11.FoodBook.model.ClientHelper.java

/**
 * Converts the given recipe to a JSON object (this includes re-encoding photos).
 * @param recipe The recipe to be converted.
 * @return A JSON version of the given recipe.
 *///from w ww. j  a  v a2 s  . c o m
public StringEntity recipeToJSON(Recipe recipe) {
    StringEntity se = null;
    ServerRecipe sr = new ServerRecipe(recipe);

    try {
        se = new StringEntity(gson.toJson(sr));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return se;

}

From source file:org.opencredo.cloud.storage.azure.model.StringBlob.java

/**
 * @return//w ww. ja va  2  s . co  m
 * @see org.opencredo.cloud.storage.azure.model.Blob#createRequestBody()
 */
@Override
public HttpEntity createRequestBody() throws AzureRestRequestCreationException {
    try {
        return new StringEntity(data);
    } catch (UnsupportedEncodingException e) {
        throw new AzureRestRequestCreationException("Usupported string encoding", e);
    }
}

From source file:httpServerClient.app.QuickStart.java

public static void sendMessage(String[] args) throws Exception {
    // arguments to run Quick start POST:
    // args[0] POST
    // args[1] IPAddress of server
    // args[2] port No.
    // args[3] user name
    // args[4] myMessage
    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {//from  w ww.j  a v  a 2 s.  co  m
        HttpPost httpPost = new HttpPost("http://" + args[1] + ":" + args[2] + "/sendMessage");
        // httpPost.setEntity(new StringEntity("lubo je kral"));
        httpPost.setEntity(
                new StringEntity("{\"name\":\"" + args[3] + "\",\"myMessage\":\"" + args[4] + "\"}"));
        CloseableHttpResponse response1 = httpclient.execute(httpPost);
        // The underlying HTTP connection is still held by the response
        // object
        // to allow the response content to be streamed directly from the
        // network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally
        // clause.
        // Please note that if response content is not fully consumed the
        // underlying
        // connection cannot be safely re-used and will be shut down and
        // discarded
        // by the connection manager.
        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();

            /*
             * Vypisanie odpovede do konzoly a discard dat zo serveru.
             */

            System.out.println(EntityUtils.toString(entity1));
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }

    } finally {
        httpclient.close();
    }
}