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:au.org.ala.biocache.service.AlaImageMetadataService.java

@Override
public Map<String, List<Map<String, Object>>> getImageMetadataForOccurrences(List<String> occurrenceIDs)
        throws Exception {
    logger.debug("Retrieving the image metadata for " + occurrenceIDs.size() + " records");
    Map<String, Object> payload = new HashMap<String, Object>();
    payload.put("key", "occurrenceid");
    payload.put("values", occurrenceIDs);

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost post = new HttpPost(imageServiceUrl + "/findImagesByMetadata");

    ObjectMapper om = new ObjectMapper();

    post.setEntity(new StringEntity(om.writeValueAsString(payload), "UTF-8"));
    HttpResponse httpResponse = httpClient.execute(post);

    String jsonResponseString = EntityUtils.toString(httpResponse.getEntity());

    Map<String, Object> jsonResponse = om.readValue(jsonResponseString, Map.class);
    Map<String, List<Map<String, Object>>> imageMetadata = (Map<String, List<Map<String, Object>>>) jsonResponse
            .get("images");
    logger.debug("Obtained image metadata for " + imageMetadata.size() + " records");
    return imageMetadata;

}

From source file:org.callimachusproject.server.chain.SecureChannelFilter.java

private BasicHttpResponse insecure() {
    String msg = "Cannot request secure resource over insecure channel";
    BasicHttpResponse resp;/*from w w  w  .j  a v  a  2  s.  com*/
    resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, 400, msg);
    resp.setEntity(new StringEntity(msg, Charset.forName("UTF-8")));
    return resp;
}

From source file:com.jeecms.common.web.ClientCustomSSL.java

public static String getInSsl(String url, File pkcFile, String storeId, String params, String contentType)
        throws Exception {
    String text = "";
    // ???PKCS12/*ww  w .j a  v  a2  s .  c  o m*/
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    // ?PKCS12?
    FileInputStream instream = new FileInputStream(pkcFile);
    try {
        // PKCS12?(ID)
        keyStore.load(instream, storeId.toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, storeId.toCharArray()).build();
    // Allow TLSv1 protocol only
    // TLS 
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    // httpclientSSLSocketFactory
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {
        HttpPost post = new HttpPost(url);
        StringEntity s = new StringEntity(params, "utf-8");
        if (StringUtils.isBlank(contentType)) {
            s.setContentType("application/xml");
        }
        s.setContentType(contentType);
        post.setEntity(s);
        HttpResponse res = httpclient.execute(post);
        HttpEntity entity = res.getEntity();
        text = EntityUtils.toString(entity, "utf-8");
    } finally {
        httpclient.close();
    }
    return text;
}

From source file:com.myandroidremote.AndroidRequestTransport.java

public void send(String payload, TransportReceiver receiver) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost();
    post.setHeader("Content-Type", "application/json;charset=UTF-8");
    post.setHeader("Cookie", cookie);

    post.setURI(uri);/*from   w w  w.  ja va  2s  .c  o m*/
    Throwable ex;
    try {
        post.setEntity(new StringEntity(payload, "UTF-8"));
        HttpResponse response = client.execute(post);
        if (200 == response.getStatusLine().getStatusCode()) {
            String contents = readStreamAsString(response.getEntity().getContent());
            receiver.onTransportSuccess(contents);
        } else {
            receiver.onTransportFailure(new ServerFailure(response.getStatusLine().getReasonPhrase()));
        }
        return;
    } catch (UnsupportedEncodingException e) {
        ex = e;
    } catch (ClientProtocolException e) {
        ex = e;
    } catch (IOException e) {
        ex = e;
    } catch (Exception e) {
        ex = e;
    }
    receiver.onTransportFailure(new ServerFailure(ex.getMessage()));
}

From source file:pl.bcichecki.rms.client.android.services.clients.restful.impl.UtilitiesRestClient.java

public void registerUser(User user, AsyncHttpResponseHandler handler) {
    String userAsJson = GsonHolder.getGson().toJson(user);
    HttpEntity userAsHttpEntity;//from ww w .j  av  a 2 s .  c om

    try {
        userAsHttpEntity = new StringEntity(userAsJson, HttpConstants.CHARSET_UTF8);
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "This system does not support required encoding.", e);
        throw new IllegalStateException("This system does not support required encoding.", e);
    }

    List<Header> headers = new ArrayList<Header>();
    RestUtils.decorareHeaderWithMD5(headers, userAsJson);

    put(getContext(), getAbsoluteAddress(RestConstants.RESOURCE_PATH_REGISTER), getHeadersAsArray(headers),
            userAsHttpEntity, HttpConstants.CONTENT_TYPE_APPLICATION_JSON_CHARSET_UTF8, handler);
}

From source file:com.infinities.keystone4j.PatchClient.java

public JsonNode connect(Object obj) throws ClientProtocolException, IOException {
    String input = JsonUtils.toJsonWithoutPrettyPrint(obj);
    logger.debug("input: {}", input);
    StringEntity requestEntity = new StringEntity(input, ContentType.create("application/json", Consts.UTF_8));

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from  w  w  w.j ava2s  .  c  om*/
        HttpPatch request = new HttpPatch(url);
        request.addHeader("accept", "application/json");
        request.addHeader("X-Auth-Token", Config.Instance.getOpt(Config.Type.DEFAULT, "admin_token").asText());
        request.setEntity(requestEntity);
        ResponseHandler<JsonNode> rh = new ResponseHandler<JsonNode>() {

            @Override
            public JsonNode handleResponse(final HttpResponse response) throws IOException {
                StatusLine statusLine = response.getStatusLine();
                HttpEntity entity = response.getEntity();
                if (entity == null) {
                    throw new ClientProtocolException("Response contains no content");
                }
                String output = getStringFromInputStream(entity.getContent());
                logger.debug("output: {}", output);
                assertEquals(200, statusLine.getStatusCode());

                JsonNode node = JsonUtils.convertToJsonNode(output);
                return node;
            }

            private String getStringFromInputStream(InputStream is) {

                BufferedReader br = null;
                StringBuilder sb = new StringBuilder();

                String line;
                try {

                    br = new BufferedReader(new InputStreamReader(is));
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (br != null) {
                        try {
                            br.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                return sb.toString();

            }
        };
        JsonNode node = httpclient.execute(request, rh);

        return node;
    } finally {
        httpclient.close();
    }
}

From source file:es.eucm.blindfaithgames.minesweeper.AndroidRequestTransport.java

public void send(String payload, TransportReceiver receiver) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost();
    post.setHeader("Content-Type", "application/json;charset=UTF-8");
    // post.setHeader("Cookie", cookie);

    post.setURI(uri);/*w w w . j ava  2s  . com*/
    Throwable ex;
    try {
        post.setEntity(new StringEntity(payload, "UTF-8"));
        HttpResponse response = client.execute(post);
        if (200 == response.getStatusLine().getStatusCode()) {
            String contents = readStreamAsString(response.getEntity().getContent());
            receiver.onTransportSuccess(contents);
        } else {
            receiver.onTransportFailure(new ServerFailure(response.getStatusLine().getReasonPhrase()));
        }
        return;
    } catch (UnsupportedEncodingException e) {
        ex = e;
    } catch (ClientProtocolException e) {
        ex = e;
    } catch (IOException e) {
        ex = e;
    }
    receiver.onTransportFailure(new ServerFailure(ex.getMessage()));
}

From source file:org.fcrepo.storage.policy.FedoraStoragePolicyIT.java

@Test
public void testPolicyCreateByPost() throws Exception {
    final HttpPost objMethod = HttpPostObjMethod(POLICY_RESOURCE);
    StringEntity input = new StringEntity(MIME_KEY + " " + MIME + " " + STORE, "UTF-8");
    input.setContentType(APPLICATION_FORM_URLENCODED);
    objMethod.setEntity(input);/*from   w w w .java 2 s.co  m*/
    final HttpResponse response = client.execute(objMethod);

    String body = IOUtils.toString(response.getEntity().getContent());
    assertEquals(body, 201, response.getStatusLine().getStatusCode());

    policyKeys.add(MIME_KEY);

    Header[] headers = response.getHeaders("Location");
    assertNotNull(headers);
    assertEquals(1, headers.length);
    assertEquals(objMethod.getURI().toString().replace(POLICY_RESOURCE, MIME_KEY), headers[0].getValue());
}

From source file:com.qcloud.project.macaovehicle.util.MessageGetter.java

public static String sendXml(String xml, String url) {

    StringBuffer buffer = new StringBuffer();
    try {/*  w ww .j  a  v  a2s .co m*/
        client = new DefaultHttpClient();
        post = new HttpPost(url);
        StringEntity stringEntity = new StringEntity(xml, "UTF-8");
        System.out.println(xml);
        stringEntity.setContentType("text/xml");
        post.setEntity(stringEntity);
        HttpResponse response = client.execute(post);// Http Post
        System.out.println(response);
        // System.out.println(response.getStatusLine());
        if (null != response && 200 == response.getStatusLine().getStatusCode()) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                // start ??
                InputStream is = entity.getContent();
                BufferedReader in = new BufferedReader(new InputStreamReader(is));
                String line = "";
                while ((line = in.readLine()) != null) {
                    buffer.append(line);
                }
                // end ??
                System.out.println("response:" + buffer.toString());
            }
        }
    } catch (Exception e) {
        logger.error(e);
    }
    return buffer.toString();
}