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:bit.changepurse.wdk.util.CheckedExceptionMethods.java

public static HttpEntity newHttpEntity(String payload) {
    try {//from   ww  w .j  a  v  a  2 s.c  om
        return new StringEntity(payload);
    } catch (UnsupportedEncodingException e) {
        throw new UncheckedException(e);
    }
}

From source file:de.tor.tribes.util.OBSTReportSender.java

public static void sendReport(URL pTarget, String pData) throws Exception {

    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);

    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Required protocol interceptors
            new RequestContent(), new RequestTargetHost(),
            // Recommended protocol interceptors
            new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpContext context = new BasicHttpContext(null);

    HttpHost host = new HttpHost(pTarget.getHost(), pTarget.getPort());

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

    try {/*from  www . j  av a2 s  . com*/
        HttpEntity[] requestBodies = { new StringEntity(pData) };

        for (int i = 0; i < requestBodies.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
                    pTarget.getPath() + "?" + pTarget.getQuery());

            request.setEntity(requestBodies[i]);
            // System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            //   System.out.println("<< Response: " + response.getStatusLine());
            // System.out.println(EntityUtils.toString(response.getEntity()));
            // System.out.println("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }
}

From source file:vng.paygate.notify.NotifyHelper.java

public String postNotify(String url, JsonObject json, String dataType, String contentType)
        throws UnsupportedEncodingException, IOException {
    try {/*from  w w w . j a v a2 s. c om*/
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        if (StringUtils.isEmpty(contentType)) {
            contentType = "application/json";
        }
        if (StringUtils.isEmpty(dataType)) {
            dataType = "application/json";
        }
        httpPost.setHeader("Content-type", contentType);
        httpPost.setHeader("Accept-Content Type", dataType);
        httpPost.setEntity(new StringEntity(json.toString()));
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = reader.readLine()) != null) {
                response.append(inputLine);
            }
            reader.close();
            return response.toString();
        } else {
            return "";
        }
    } catch (Exception e) {
        return "";
    }
}

From source file:com.alignace.chargeio.net.Requestor.java

public ServerResponse post(String url, Map<String, String> headers, String data)
        throws UnsupportedEncodingException {

    HttpPost post = new HttpPost(url);

    for (String key : headers.keySet())
        post.setHeader(key, headers.get(key));

    post.setEntity(new StringEntity(data));
    return executeRequest(post);
}

From source file:com.flexilogix.HTTPNotifierFunction.java

public void call(Tuple5<Long, String, Float, Float, String> tweet) {
    String webserver = Properties.getString("rts.spark.webserv");
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(webserver);
    String content = String.format("{\"id\": \"%d\", " + "\"text\": \"%s\", " + "\"pos\": \"%f\", "
            + "\"neg\": \"%f\", " + "\"score\": \"%s\" }", tweet._1(), tweet._2(), tweet._3(), tweet._4(),
            tweet._5());/* w ww  . ja v  a2 s .c  o  m*/

    try {
        post.setEntity(new StringEntity(content));
        HttpResponse response = client.execute(post);
        org.apache.http.util.EntityUtils.consume(response.getEntity());
    } catch (Exception ex) {
        Logger LOG = Logger.getLogger(this.getClass());
        LOG.error("exception thrown while attempting to post", ex);
        LOG.trace(null, ex);
    }
}

From source file:com.gamethrive.GameThriveRestClient.java

static void put(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.put(context, BASE_URL + url, entity, "application/json", responseHandler);
        }//from w ww.ja  v a 2  s  .  c o m
    }).start();
}

From source file:com.meschbach.psi.util.rest.StringEntityBuilder.java

/**
 * @see EntityBuilder/*w ww.  ja  v a2s .c  om*/
 */
public HttpEntity buildEntity() throws PSIException {
    try {
        return new StringEntity(entity);
    } catch (UnsupportedEncodingException uee) {
        throw new PSIException("Unable to create HTTP entity", uee);
    }
}

From source file:com.rastating.droidbeard.net.ErrorReportTask.java

public JSONObject postData(String url, JSONObject obj) {
    HttpClient client = new DefaultHttpClient();
    String json = obj.toString();

    try {//from  ww w.  j a  va  2s. co m
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-type", "application/json");

        StringEntity se = new StringEntity(obj.toString());
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        post.setEntity(se);

        HttpResponse response = client.execute(post);
        String retval = EntityUtils.toString(response.getEntity());

        return new JSONObject(retval);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.butler.service.PushNotifier.java

private void send() {
    try {/*from   w ww. ja  va2s  . co m*/
        String url = "https://android.googleapis.com/gcm/send";
        HttpClient client = new DefaultHttpClient();
        HttpPost request = new HttpPost(url);
        request.addHeader("Authorization", "key=AIzaSyCBODt7lH-oPSKiZJ5MJlugTS0BV3U-KGc");
        request.addHeader("Content-Type", "application/json");
        Header header = new Header();
        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        String rawData = ow.writeValueAsString(header);
        request.setEntity(new StringEntity(rawData));
        HttpResponse response = client.execute(request);
        // System.out.println("response"+IOUtils.toString(response.getEntity().getContent()));
    } catch (Exception ex) {
        Logger.getLogger(PushNotifier.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:io.liveoak.container.ParamsServerTest.java

@Test
public void testServer() throws Exception {

    Header header = new BasicHeader("Accept", "application/json");

    HttpGet getRequest = null;//w w  w.  j a v a 2  s  .c o m
    HttpPost postRequest = null;
    HttpPut putRequest = null;
    CloseableHttpResponse response = null;

    // create people collection with direct PUT
    System.err.println("CREATE /people collection");

    putRequest = new HttpPut("http://localhost:8080/testApp/memory/people");
    putRequest.setEntity(new StringEntity("{ \"type\": \"collection\" }"));
    putRequest.setHeader("Content-Type", "application/json");
    response = this.httpClient.execute(putRequest);
    System.err.println("response: " + response);
    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(201);

    response.close();

    System.err.println("PREPARE 2 people ...");
    // Post a person

    postRequest = new HttpPost("http://localhost:8080/testApp/memory/people");
    postRequest.setEntity(new StringEntity("{ \"name\": \"bob\" }"));
    postRequest.setHeader("Content-Type", "application/json");

    response = httpClient.execute(postRequest);
    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(201);

    ResourceState bobState = decode(response);
    assertThat(bobState).isNotNull();

    assertThat(bobState.id()).isNotNull();
    assertThat(bobState.getProperty("name")).isEqualTo("bob");

    response.close();

    postRequest = new HttpPost("http://localhost:8080/testApp/memory/people");
    postRequest.setEntity(new StringEntity("{ \"name\": \"krusty\" }"));
    postRequest.setHeader("Content-Type", "application/json");

    response = httpClient.execute(postRequest);
    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(201);

    ResourceState krustyState = (ResourceState) decode(response);
    assertThat(krustyState).isNotNull();

    //assertThat(krustyState.getProperty(LiveOak.ID)).isNotNull();
    assertThat(krustyState.id()).isNotNull();
    assertThat(krustyState.getProperty("name")).isEqualTo("krusty");

    response.close();

    System.err.println("TEST #1");
    // test pagination

    // now that we have two people we can do paging requests

    // Retrieve first people resource, ensuring only the first one is returned
    // Assumption: unsorted GET on collection returns items in the order they were added to collection
    getRequest = new HttpGet("http://localhost:8080/testApp/memory/people?limit=1");
    getRequest.addHeader(header);
    response = httpClient.execute(getRequest);

    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);

    ResourceState state = decode(response);
    assertThat(state).isNotNull();
    List<ResourceState> members = state.members();

    assertThat(members.size()).isEqualTo(1);

    ResourceState memberState = members.get(0);
    assertThat(memberState).isInstanceOf(ResourceState.class);

    ResourceState member = (ResourceState) memberState;
    assertThat(member.id()).isEqualTo(bobState.id());

    response.close();

    // Retrieve second people resource, ensuring only the second one is returned
    // Assumption: unsorted GET on collection returns items in the order they were added to collection
    getRequest = new HttpGet("http://localhost:8080/testApp/memory/people?offset=1&limit=1");
    getRequest.addHeader(header);
    response = httpClient.execute(getRequest);

    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);

    state = decode(response);
    assertThat(state).isNotNull();

    members = state.members();
    assertThat(members.size()).isEqualTo(1);

    memberState = members.get(0);
    assertThat(memberState).isInstanceOf(ResourceState.class);

    member = (ResourceState) memberState;
    assertThat(member.id()).isEqualTo(krustyState.id());

    response.close();

    // Retrieve the people resource with a limit of 0 (eg do not return any members)
    getRequest = new HttpGet("http://localhost:8080/testApp/memory/people?limit=0");
    getRequest.addHeader(header);
    response = httpClient.execute(getRequest);

    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);

    state = decode(response);
    assertThat(state).isNotNull();

    members = state.members();
    assertThat(members.size()).isEqualTo(0);

    response.close();

    System.err.println("TEST #2");
    // test specifying fields to return

    getRequest = new HttpGet("http://localhost:8080/testApp/memory/people/" + krustyState.id() + "?fields=id");
    getRequest.addHeader(header);
    response = httpClient.execute(getRequest);

    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);

    state = decode(response);
    assertThat(state).isNotNull();
    assertThat(state).isInstanceOf(ResourceState.class);

    HashSet fields = new HashSet();
    /*
    ((CollectionResourceState) state).members().forEach((f) -> {
    fields.add(f.id());
    });
    */
    // TODO: uncomment when _self, and id encoding takes ReturnFields into account
    //assertThat(fields.size()).isEqualTo(1);
    //assertThat(fields.contains("id")).isTrue();
    //assertThat(fields.contains("name")).isFalse();
}