List of usage examples for org.apache.http.entity StringEntity StringEntity
public StringEntity(String str, Charset charset)
From source file:de.dev.eth0.elasticsearch.aem.search.Search.java
public SearchResult perform() { try {//from w w w . ja va2 s .co m ObjectMapper mapper = new ObjectMapper(); String queryString = serialize(); LOG.info("Query: " + queryString); Response response = elasticSearchService.getRestClient().performRequest("GET", "/" + index + "/_search", Collections.<String, String>emptyMap(), new StringEntity(queryString, "UTF-8")); HttpEntity entity = response.getEntity(); return mapper.readValue(entity.getContent(), SearchResult.class); } catch (IOException ex) { LOG.error("Could not perform query", ex); } return null; }
From source file:org.thiesen.osm.pt.SolrPoster.java
private void postToSolr(final String content) throws IOException { final HttpClient client = new DefaultHttpClient(); final HttpPost method = new HttpPost("http://hhpt-search.appspot.com/update"); method.setHeader("Content-Type", "application/xml; charset=utf8"); method.setEntity(new StringEntity("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + content, "utf8")); client.execute(method);//from w w w.j a v a 2 s.com System.out.println("Executed update"); }
From source file:ly.apps.android.rest.converters.impl.JacksonBodyConverter.java
@Override public <T> HttpEntity toRequestBody(T object, String contentType) { Logger.d("JacksonBodyConverter.toRequestBody: object: " + object); try {/*from w ww.ja v a2 s . c om*/ String json = mapper.writeValueAsString(object); Logger.d("JacksonHttpFormValuesConverter.toRequestBody: json: " + json); StringEntity result = new StringEntity(json, "UTF-8"); result.setContentType(contentType); Logger.d("JacksonBodyConverter.toRequestBody: result: " + result); return result; } catch (UnsupportedEncodingException e) { throw new SerializationException(e); } catch (JsonMappingException e) { throw new SerializationException(e); } catch (JsonGenerationException e) { throw new SerializationException(e); } catch (IOException e) { throw new SerializationException(e); } }
From source file:net.data.technology.jraft.extensions.http.HttpRpcClient.java
@Override public CompletableFuture<RaftResponseMessage> send(RaftRequestMessage request) { CompletableFuture<RaftResponseMessage> future = new CompletableFuture<RaftResponseMessage>(); String payload = this.gson.toJson(request); HttpPost postRequest = new HttpPost(this.serverUrl); postRequest.setEntity(new StringEntity(payload, StandardCharsets.UTF_8)); this.httpClient.execute(postRequest, new FutureCallback<HttpResponse>() { @Override//from ww w .ja va2 s . c o m public void completed(HttpResponse result) { if (result.getStatusLine().getStatusCode() != 200) { logger.info("receive an response error code " + String.valueOf(result.getStatusLine().getStatusCode()) + " from server"); future.completeExceptionally(new IOException("Service Error")); } try { InputStreamReader reader = new InputStreamReader(result.getEntity().getContent()); RaftResponseMessage response = gson.fromJson(reader, RaftResponseMessage.class); future.complete(response); } catch (Throwable error) { logger.info("fails to parse the response from server due to errors", error); future.completeExceptionally(error); } } @Override public void failed(Exception ex) { future.completeExceptionally(ex); } @Override public void cancelled() { future.completeExceptionally(new IOException("request cancelled")); } }); return future; }
From source file:org.elasticsearch.xpack.ml.integration.MlPluginDisabledIT.java
/** * Check that when the ml plugin is disabled, you cannot create a job as the * rest handler is not registered// ww w . java 2 s . co m */ public void testActionsFail() throws Exception { XContentBuilder xContentBuilder = jsonBuilder(); xContentBuilder.startObject(); xContentBuilder.field("actions-fail-job", "foo"); xContentBuilder.field("description", "Analysis of response time by airline"); xContentBuilder.startObject("analysis_config"); xContentBuilder.field("bucket_span", "3600s"); xContentBuilder.startArray("detectors"); xContentBuilder.startObject(); xContentBuilder.field("function", "metric"); xContentBuilder.field("field_name", "responsetime"); xContentBuilder.field("by_field_name", "airline"); xContentBuilder.endObject(); xContentBuilder.endArray(); xContentBuilder.endObject(); xContentBuilder.startObject("data_description"); xContentBuilder.field("format", "xcontent"); xContentBuilder.field("time_field", "time"); xContentBuilder.field("time_format", "epoch"); xContentBuilder.endObject(); xContentBuilder.endObject(); ResponseException exception = expectThrows(ResponseException.class, () -> client().performRequest("put", MachineLearning.BASE_PATH + "anomaly_detectors/foo", Collections.emptyMap(), new StringEntity(Strings.toString(xContentBuilder), ContentType.APPLICATION_JSON))); assertThat(exception.getMessage(), containsString("no handler found for uri [/_xpack/ml/anomaly_detectors/foo] and method [PUT]")); }
From source file:org.eclipse.winery.common.config.externalservice.msb.HttpClientUtil.java
/** * send http post request./*from www . ja v a 2 s. c o m*/ * * @param parameters post request parameters * @return response context */ public String post(String parameters) { String body = null; logger.info("apiURl" + this.apiUrl + " parameters:" + parameters); if (method != null & parameters != null && !"".equals(parameters.trim())) { try { method.addHeader("Content-type", "application/json; charset=utf-8"); method.setHeader("Accept", "application/json"); method.setEntity(new StringEntity(parameters, Charset.forName("UTF-8"))); startTime = System.currentTimeMillis(); HttpResponse response = httpClient.execute(method); endTime = System.currentTimeMillis(); int statusCode = response.getStatusLine().getStatusCode(); logger.info("statusCode:" + statusCode); logger.info("Call API to spend time(Unit:ms):" + (endTime - startTime)); if (statusCode != HttpStatus.SC_CREATED) { logger.error("post Method failed:" + response.getStatusLine()); status = 1; } body = EntityUtils.toString(response.getEntity()); } catch (IOException e1) { logger.error("post Method failed,errormsg:" + e1.getMessage()); status = 3; } finally { logger.info("Call API status:" + status); } } return body; }
From source file:com.pyz.tool.weixintool.util.HttpTool.java
public static String postRequest(String url, String content) throws Exception { String result = ""; HttpClient httpClient = new DefaultHttpClient(); try {//from w w w .j a v a 2 s. com HttpPost httppost = new HttpPost(url); StringEntity myEntity = new StringEntity(content, "utf-8"); myEntity.setContentEncoding("utf-8"); myEntity.setContentType("application/json"); httppost.setEntity(myEntity); HttpResponse httpresponse = httpClient.execute(httppost); HttpEntity entity = httpresponse.getEntity(); result = EntityUtils.toString(entity); } catch (ParseException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; }
From source file:com.weitaomi.systemconfig.wechat.ClientCustomSSL.java
public static String connectKeyStore(String url, String xml, String path, int flag) throws Exception { KeyStore keyStore = KeyStore.getInstance("PKCS12"); File file = LoadFileFactory.getFile(path); char[] arr = null; if (flag == 0) { arr = WechatConfig.MCHID.toCharArray(); }/*from www . j av a 2 s. c o m*/ if (flag == 1) { arr = WechatConfig.MCHID_OFFICIAL.toCharArray(); } FileInputStream instream = new FileInputStream(file); try { keyStore.load(instream, arr); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, arr).build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); StringEntity entityRequest = new StringEntity(xml, "utf-8"); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(entityRequest); // httpPost.setHeader("Content-Type", "application/json");//; charset=utf-8 HttpResponse response = httpclient.execute(httpPost); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new RuntimeException(""); } HttpEntity resEntity = response.getEntity(); InputStream inputStream = resEntity.getContent(); return HttpRequestUtils.readInstream(inputStream, "UTF-8"); }
From source file:org.alfresco.provision.BMService.java
/** * Populate HTTP message call with given content. * // www.j a va2s .c om * @param content * String content * @return {@link StringEntity} content. * @throws UnsupportedEncodingException * if unsupported */ public StringEntity setMessageBody(final String content) throws UnsupportedEncodingException { if (content == null || content.isEmpty()) throw new UnsupportedOperationException("Content is required."); return new StringEntity(content, UTF_8_ENCODING); }
From source file:qhindex.servercomm.ServerDataCache.java
public JSONObject sendRequest(JSONObject data, String url, boolean sentAdminNotification) { JSONObject obj = new JSONObject(); final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(AppHelper.connectionTimeOut) .setConnectionRequestTimeout(AppHelper.connectionTimeOut) .setSocketTimeout(AppHelper.connectionTimeOut).setStaleConnectionCheckEnabled(true).build(); final CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build(); HttpPost httpPost = new HttpPost(url); String dataStr = data.toJSONString(); dataStr = dataStr.replaceAll("null", "\"\""); if (sentAdminNotification == true) { try {/*from w w w . ja v a2 s . c o m*/ AdminMail adminMail = new AdminMail(); adminMail.sendMailToAdmin("Data to send to the server.", dataStr); } catch (Exception ex) { // Catch any problem during this step and continue Debug.print("Could not send admin notification e-mail: " + ex); } } Debug.print("DATA REQUEST: " + dataStr); StringEntity jsonData = new StringEntity(dataStr, ContentType.create("plain/text", Consts.UTF_8)); jsonData.setChunked(true); httpPost.addHeader("content-type", "application/json"); httpPost.addHeader("accept", "application/json"); httpPost.setEntity(jsonData); try (CloseableHttpResponse response = httpclient.execute(httpPost)) { StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() >= 300) { Debug.print("Exception while sending http request: " + statusLine.getStatusCode() + " : " + statusLine.getReasonPhrase()); resultsMsg += "Exception while sending http request: " + statusLine.getStatusCode() + " : " + statusLine.getReasonPhrase() + "\n"; } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output = new String(); String line; while ((line = br.readLine()) != null) { output += line; } output = output.substring(output.indexOf('{')); try { obj = (JSONObject) new JSONParser().parse(output); } catch (ParseException pEx) { Debug.print( "Could not parse internet response. It is possible the cache server fail to deliver the content: " + pEx.toString()); resultsMsg += "Could not parse internet response. It is possible the cache server fail to deliver the content.\n"; } } catch (IOException ioEx) { Debug.print("Could not handle the internet request: " + ioEx.toString()); resultsMsg += "Could not handle the internet request.\n"; } return obj; }