List of usage examples for org.apache.http.entity StringEntity StringEntity
public StringEntity(String str, Charset charset)
From source file:com.shmsoft.dmass.lotus.SolrConnector.java
protected void sendPostCommand(String point, String param) throws Exception { HttpClient httpClient = new DefaultHttpClient(); HttpPost request = new HttpPost(point); StringEntity params = new StringEntity(param, HTTP.UTF_8); params.setContentType("text/xml"); request.setEntity(params);/* ww w . j a va2 s . c o m*/ HttpResponse response = httpClient.execute(request); response.getStatusLine().getStatusCode(); }
From source file:br.ufg.inf.horus.implementation.service.HttpRequest.java
/** * Mtodo que executa o POST.//from ww w. j ava 2s. c o m * * @see HttpInterface * @param url Url para a requisio. * @param body Mensagem da requisio. * @param log Objeto para exibio de mensagens Log (opcional). * @return Resposta da requisio. */ @Override public String request(String url, String body, Log log) throws BsusException { BsusValidator.verifyNull(body, " body", log); BsusValidator.verifyNull(url, " url", log); String resposta = ""; try { CloseableHttpClient httpclient = HttpClientBuilder.create().build(); StringEntity strEntity = new StringEntity(body, "UTF-8"); strEntity.setContentType("text/xml"); HttpPost post = new HttpPost(url); post.setEntity(strEntity); HttpResponse response = httpclient.execute(post); HttpEntity respEntity = response.getEntity(); resposta = EntityUtils.toString(respEntity); } catch (IOException e) { String message = "Houve um erro ao abrir o documento .xml"; BsusValidator.catchException(e, message, log); } catch (UnsupportedCharsetException e) { String message = "O charset 'UTF-8' da mensagem no esta sendo suportado."; BsusValidator.catchException(e, message, log); } catch (ParseException e) { String message = "Houve um erro ao buscar as informaes."; BsusValidator.catchException(e, message, log); } return resposta; }
From source file:gobblin.writer.http.RestWriter.java
@Override public Optional<HttpUriRequest> onNewRecord(RestEntry<String> record) { HttpUriRequest uriRequest = RequestBuilder.post() .addHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType()) .setUri(combineUrl(getCurServerHost(), record.getResourcePath())) .setEntity(new StringEntity(record.getRestEntryVal(), ContentType.TEXT_PLAIN)).build(); return Optional.of(uriRequest); }
From source file:org.privatenotes.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 www .j a v a 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"); HttpResponse response = execute(httpPut); return parseResponse(response); }
From source file:boosta.artem.services.TaskQuery.java
public int addTask() throws UnsupportedEncodingException, IOException, ParseException { int task_id = 0; DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://62.210.82.210:9091/API"); StringEntity requestEntity = new StringEntity(this.task.toJSON(), "UTF-8"); requestEntity.setContentType("application/json"); System.out.println(getStringFromInputStream(requestEntity.getContent()) + "\n"); httpPost.setEntity(requestEntity);//ww w.j av a2 s. c om HttpResponse response = httpClient.execute(httpPost); InputStream in = response.getEntity().getContent(); String resp = getStringFromInputStream(in); //resp.getBytes("UTF-8"); //resp = resp.getBytes(resp).toString(); System.out.println(resp); JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(resp); //json.toJSONString(); task_id = Integer.parseInt(json.get("data").toString()); System.out.println(task_id); return task_id; }
From source file:gobblin.writer.http.RestJsonWriter.java
@Override public Optional<HttpUriRequest> onNewRecord(RestEntry<JsonObject> record) { HttpUriRequest uriRequest = RequestBuilder.post() .addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()) .setUri(combineUrl(getCurServerHost(), record.getResourcePath())) .setEntity(new StringEntity(record.getRestEntryVal().toString(), ContentType.APPLICATION_JSON)) .build();/*w ww . j a va 2 s . com*/ return Optional.of(uriRequest); }
From source file:ch.ralscha.extdirectspring_itest.RawJsonControllerTest.java
@SuppressWarnings("unchecked") private static void testAndCheck(String action, String method, Integer total, boolean success) throws IOException, JsonParseException, JsonMappingException { CloseableHttpClient client = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; try {/*from ww w. j a va2 s.co m*/ HttpPost post = new HttpPost("http://localhost:9998/controller/router"); StringEntity postEntity = new StringEntity("{\"action\":\"" + action + "\",\"method\":\"" + method + "\",\"data\":[],\"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("[").endsWith("]"); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> rootAsMap = mapper .readValue(responseString.substring(1, responseString.length() - 1), Map.class); assertEquals(5, rootAsMap.size()); assertEquals(method, rootAsMap.get("method")); assertEquals("rpc", rootAsMap.get("type")); assertEquals(action, rootAsMap.get("action")); assertEquals(1, rootAsMap.get("tid")); Map<String, Object> result = (Map<String, Object>) rootAsMap.get("result"); if (total != null) { assertEquals(3, result.size()); assertThat((Integer) result.get("total")).isEqualTo(total); } else { assertEquals(2, result.size()); } assertThat((Boolean) result.get("success")).isEqualTo(success); List<Map<String, Object>> records = (List<Map<String, Object>>) result.get("records"); assertEquals(2, records.size()); assertEquals("4cf8e5b8924e23349fb99454", ((Map<String, Object>) records.get(0).get("_id")).get("$oid")); assertEquals("4cf8e5b8924e2334a0b99454", ((Map<String, Object>) records.get(1).get("_id")).get("$oid")); } finally { IOUtils.closeQuietly(response); IOUtils.closeQuietly(client); } }
From source file:com.srotya.tau.alerts.media.HttpService.java
/** * @param alert//from w ww . j ava 2 s .co m * @throws AlertDeliveryException */ public void sendHttpCallback(Alert alert) throws AlertDeliveryException { try { CloseableHttpClient client = Utils.buildClient(alert.getTarget(), 3000, 3000); HttpPost request = new HttpPost(alert.getTarget()); StringEntity body = new StringEntity(alert.getBody(), ContentType.APPLICATION_JSON); request.addHeader("content-type", "application/json"); request.setEntity(body); HttpResponse response = client.execute(request); EntityUtils.consume(response.getEntity()); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode < 200 && statusCode >= 300) { throw exception; } client.close(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | IOException | AlertDeliveryException e) { throw exception; } }
From source file:org.alfresco.utils.HttpUtil.java
/** * Populate HTTP message call with given content. * /*from w w w . ja v a 2 s .c o m*/ * @param content String content * @return {@link StringEntity} content. * @throws UnsupportedEncodingException if unsupported */ public static StringEntity setMessageBody(final String content) throws UnsupportedEncodingException { if (content == null || content.isEmpty()) { throw new IllegalArgumentException("Content is required."); } return new StringEntity(content, UTF_8_ENCODING); }
From source file:com.nominanuda.hyperapi.HyperApiWsSkeltonTest.java
@Test public void testFoo() throws Exception { HyperApiWsSkelton skelton = new HyperApiWsSkelton(); skelton.setApi(TestHyperApi.class); skelton.setService(new TestHyperApi() { public DataObject putFoo(String bar, String baz, DataObject foo) { return foo; }/*from w w w . java2s .c om*/ }); skelton.setRequestUriPrefix("/mytest"); HttpPut request = new HttpPut("/mytest/foo/BAR?baz=BAZ"); DataObject foo = new DataObjectImpl(); foo.put("foo", "FOO"); request.setEntity(new StringEntity(new DataStructHelper().toJsonString(foo), ContentType.create(HttpProtocol.CT_APPLICATION_JSON, HttpProtocol.CS_UTF_8))); HttpResponse response = skelton.handle(request); DataStruct result = new JSONParser().parse(new InputStreamReader(response.getEntity().getContent())); Assert.assertEquals("FOO", ((DataObject) result).get("foo")); }