List of usage examples for org.apache.http.entity StringEntity StringEntity
public StringEntity(String str, Charset charset)
From source file:cn.hhh.myandroidserver.response.AndServerTestHandler.java
@Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { // ?key-value Map<String, String> params = HttpRequestParser.parse(request); StringBuilder stringBuilder = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { stringBuilder.append(entry.getKey() + ": " + entry.getValue() + "\r\n"); }//from w w w.j a v a2 s .com System.out.println("???" + stringBuilder.toString()); StringEntity stringEntity = new StringEntity("??", "utf-8"); response.setEntity(stringEntity); // ?UIHandler?? }
From source file:org.elasticsearch.smoketest.ReindexFromOldRemoteIT.java
private void oldEsTestCase(String portPropertyName, String requestsPerSecond) throws IOException { int oldEsPort = Integer.parseInt(System.getProperty(portPropertyName)); try (RestClient oldEs = RestClient.builder(new HttpHost("127.0.0.1", oldEsPort)).build()) { try {//from ww w . ja va2 s . c o m HttpEntity entity = new StringEntity("{\"settings\":{\"number_of_shards\": 1}}", ContentType.APPLICATION_JSON); oldEs.performRequest("PUT", "/test", singletonMap("refresh", "true"), entity); entity = new StringEntity("{\"test\":\"test\"}", ContentType.APPLICATION_JSON); oldEs.performRequest("PUT", "/test/doc/testdoc1", singletonMap("refresh", "true"), entity); oldEs.performRequest("PUT", "/test/doc/testdoc2", singletonMap("refresh", "true"), entity); oldEs.performRequest("PUT", "/test/doc/testdoc3", singletonMap("refresh", "true"), entity); oldEs.performRequest("PUT", "/test/doc/testdoc4", singletonMap("refresh", "true"), entity); oldEs.performRequest("PUT", "/test/doc/testdoc5", singletonMap("refresh", "true"), entity); entity = new StringEntity("{\n" + " \"source\":{\n" + " \"index\": \"test\",\n" + " \"size\": 1,\n" + " \"remote\": {\n" + " \"host\": \"http://127.0.0.1:" + oldEsPort + "\"\n" + " }\n" + " },\n" + " \"dest\": {\n" + " \"index\": \"test\"\n" + " }\n" + "}", ContentType.APPLICATION_JSON); Map<String, String> params = new TreeMap<>(); params.put("refresh", "true"); params.put("pretty", "true"); if (requestsPerSecond != null) { params.put("requests_per_second", requestsPerSecond); } client().performRequest("POST", "/_reindex", params, entity); Response response = client().performRequest("POST", "test/_search", singletonMap("pretty", "true")); String result = EntityUtils.toString(response.getEntity()); assertThat(result, containsString("\"_id\" : \"testdoc1\"")); } finally { oldEs.performRequest("DELETE", "/test"); } } }
From source file:io.logspace.agent.hq.HqClient.java
private static StringEntity toJsonEntity(Collection<Event> event) throws IOException { return new StringEntity(EventJsonSerializer.toJson(event), APPLICATION_JSON); }
From source file:com.att.voice.TTS.java
public void say(String text, String file) { text = text.replace("\"", ""); try {/*from ww w. j av a 2 s. c o m*/ HttpPost httpPost = new HttpPost("https://api.att.com/speech/v3/textToSpeech"); httpPost.setHeader("Authorization", "Bearer " + mAuthToken); httpPost.setHeader("Accept", "audio/x-wav"); httpPost.setHeader("Content-Type", "text/plain"); httpPost.setHeader("Tempo", "-16"); HttpEntity entity = new StringEntity(text, "UTF-8"); httpPost.setEntity(entity); HttpResponse response = httpclient.execute(httpPost); //String result = EntityUtils.toString(response.getEntity()); HttpEntity result = response.getEntity(); BufferedInputStream bis = new BufferedInputStream(result.getContent()); String filePath = System.getProperty("user.dir") + tempFile; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filePath))); int inByte; while ((inByte = bis.read()) != -1) { bos.write(inByte); } bis.close(); bos.close(); executeOnCommandLine("afplay " + System.getProperty("user.dir") + "/" + tempFile); } catch (Exception ex) { System.err.println(ex.getMessage()); } }
From source file:com.ibm.ra.remy.web.utils.BusinessRulesUtils.java
/** * Invoke Business Rules with JSON content * * @param content The payload of itineraries to send to Business Rules. * @return A JSON string representing the output of Business Rules. *//*from w w w . ja v a2 s . c om*/ public static String invokeRulesService(String json) throws Exception { PropertiesReader constants = PropertiesReader.getInstance(); String username = constants.getStringProperty(USERNAME_KEY); String password = constants.getStringProperty(PASSWORD_KEY); String endpoint = constants.getStringProperty(EXECUTION_REST_URL_KEY) + constants.getStringProperty(RULE_APP_PATH_KEY); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultCredentialsProvider(credentialsProvider).build(); String responseString = ""; try { HttpPost httpPost = new HttpPost(endpoint); httpPost.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); StringEntity jsonEntity = new StringEntity(json, MessageUtils.ENCODING); httpPost.setEntity(jsonEntity); CloseableHttpResponse response = httpClient.execute(httpPost); try { HttpEntity entity = response.getEntity(); responseString = EntityUtils.toString(entity, MessageUtils.ENCODING); EntityUtils.consume(entity); } finally { response.close(); } } finally { httpClient.close(); } return responseString; }
From source file:org.changhong.sync.web.AnonymousConnection.java
@Override public String put(String uri, String data) throws UnknownHostException { // Prepare a request object HttpPut httpPut = new HttpPut(uri); try {//from ww w .j a va 2 s.c o m // The default http content charset is ISO-8859-1, JSON requires UTF-8 httpPut.setEntity(new StringEntity(data, "UTF-8")); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); return null; } httpPut.setHeader("Content-Type", "application/json"); httpPut.addHeader("X-Tomboy-Client", Tomdroid.HTTP_HEADER); HttpResponse response = execute(httpPut); return parseResponse(response); }
From source file:com.saltedge.sdk.network.SERestClient.java
public static boolean post(String servicePath, String jsonRequest, SEHTTPResponseHandler responseHandler, HashMap<String, String> headers) { if (isNetworkUnavailable() || responseHandler == null) { return false; }/*from ww w .jav a 2 s. c o m*/ AsyncHttpClient client = createHttpClient(headers); RequestHandle handler = null; try { handler = client.post(SaltEdgeSDK.getInstance().getContext(), getAbsoluteUrl(servicePath), new StringEntity(jsonRequest, HTTP.UTF_8), SEConstants.MIME_TYPE_JSON, responseHandler); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return (handler != null); }
From source file:ch.ralscha.extdirectspring_itest.TransactionalServiceTest.java
@Test public void callClassbasedProxy() throws IOException, JsonParseException, JsonMappingException { CloseableHttpClient client = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; try {/* www .j a v a 2 s. co m*/ HttpPost post = new HttpPost("http://localhost:9998/controller/router"); StringEntity postEntity = new StringEntity( "{\"action\":\"transactionalService\",\"method\":\"setDate\",\"data\":[103,\"27/04/2012\"],\"type\":\"rpc\",\"tid\":1}", "UTF-8"); post.setEntity(postEntity); post.setHeader("Content-Type", "application/json; charset=UTF-8"); response = client.execute(post); HttpEntity entity = response.getEntity(); assertThat(entity).isNotNull(); String responseString = EntityUtils.toString(entity); assertThat(responseString).isNotNull(); assertThat(responseString.startsWith("[") && responseString.endsWith("]")).isTrue(); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> rootAsMap = mapper .readValue(responseString.substring(1, responseString.length() - 1), Map.class); assertThat(rootAsMap).hasSize(5); assertThat(rootAsMap.get("result")).isEqualTo("103,27.04.2012"); assertThat(rootAsMap.get("method")).isEqualTo("setDate"); assertThat(rootAsMap.get("type")).isEqualTo("rpc"); assertThat(rootAsMap.get("action")).isEqualTo("transactionalService"); assertThat(rootAsMap.get("tid")).isEqualTo(1); } finally { IOUtils.closeQuietly(response); IOUtils.closeQuietly(client); } }
From source file:de.devbliss.apitester.factory.impl.EntityBuilder.java
/** * Builds an entity from a given raw payload. If the payload is a string, it is directly used as payload, and the * entity's content type is text/plain, otherwise, it is serialized to JSON and the content type is set to * application/json./* w w w . j av a 2s .co m*/ * * @param payload payload which must not be null * @return entity * @throws IOException */ public StringEntity buildEntity(Object payload) throws IOException { boolean payloadIsString = payload instanceof String; String payloadAsString; if (payloadIsString) { payloadAsString = (String) payload; } else { payloadAsString = gson.toJson(payload); } StringEntity entity = new StringEntity(payloadAsString, ENCODING); if (payloadIsString) { entity.setContentType(ContentType.TEXT_PLAIN.getMimeType()); } else { entity.setContentType(ContentType.APPLICATION_JSON.getMimeType()); } return entity; }
From source file:com.google.mr4c.message.HttpMessageHandler.java
public void handleMessage(Message msg) throws IOException { HttpPost post = new HttpPost(m_uri); post.setEntity(new StringEntity(msg.getContent(), ContentType.create(msg.getContentType()))); s_log.info("POSTing message to [{}]: [{}]", m_uri, msg); HttpResponse response = m_client.execute(post); StatusLine statusLine = response.getStatusLine(); s_log.info("Status line: {}", statusLine); s_log.info("Content: {}", toString(response.getEntity())); if (statusLine.getStatusCode() >= 300) { throw new IOException(statusLine.toString()); }/*from w w w.jav a2 s.c o m*/ }