List of usage examples for org.apache.http.entity StringEntity StringEntity
public StringEntity(String str, Charset charset)
From source file:com.macrossx.wechat.impl.WechatMenuHelper.java
/** * create menu/*from w ww. ja va 2 s . c o m*/ * * @param menu * menu to create * {@link https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141013&token=&lang=zh_CN} * @return true sucess */ @Override public boolean createMenu(List<WechatButton> menu) { try { Map<String, List<WechatButton>> menus = Maps.newConcurrentMap(); menus.put("button", menu); Optional<WechatAccessToken> token = wechatHelper.getAccessToken(); if (token.isPresent()) { WechatAccessToken accessToken = token.get(); HttpPost httpPost = new HttpPost(); httpPost.setEntity(new StringEntity(new Gson().toJson(menus), "utf-8")); httpPost.setURI(new URI( MessageFormat.format(WechatConstants.MENU_CREATE_URL, accessToken.getAccess_token()))); Optional<WechatResponseObj> response = new WechatHttpClient().send(httpPost, WechatResponseObj.class); if (response.isPresent()) { WechatResponseObj e = response.get(); log.info(e.toString()); if (0 == e.getErrcode()) { return true; } } } } catch (URISyntaxException e) { log.info(e.getMessage()); } return false; }
From source file:eu.over9000.cathode.resources.implementations.FeedImpl.java
@Override public Result<PostBox> postPost(final String channelName, final PostOptions options) { return dispatcher.performPost(PostBox.class, Feed.PATH + "/" + channelName + "/posts", options == null ? null : new StringEntity(options.encode(), ContentType.APPLICATION_JSON)); }
From source file:juzu.impl.bridge.context.AbstractContextClientTestCase.java
protected void test(URL initialURL, String kind) throws Exception { driver.get(initialURL.toString());/*from ww w. ja va 2s . c o m*/ WebElement link = driver.findElement(By.id(kind)); contentLength = -1; charset = null; contentType = null; content = null; URL url = new URL(link.getAttribute("href")); DefaultHttpClient client = new DefaultHttpClient(); // Little trick to force redirect after post client.setRedirectStrategy(new DefaultRedirectStrategy() { @Override protected boolean isRedirectable(String method) { return true; } }); try { HttpPost post = new HttpPost(url.toURI()); post.setEntity(new StringEntity("foo", ContentType.create("application/octet-stream", "UTF-8"))); HttpResponse response = client.execute(post); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(3, contentLength); assertEquals("UTF-8", charset); assertEquals("application/octet-stream; charset=UTF-8", contentType); assertEquals("foo", content); assertEquals(kind, AbstractContextClientTestCase.kind); } finally { client.getConnectionManager().shutdown(); } }
From source file:com.redhat.refarch.microservices.trigger.service.TriggerService.java
public JSONObject doPurchase() throws Exception { HttpClient client = new DefaultHttpClient(); //get a customer JSONObject jsonObject = new JSONObject(); jsonObject.put("username", "bobdole"); jsonObject.put("password", "password"); URIBuilder uriBuilder = getUriBuilder("customers", "authenticate"); HttpPost post = new HttpPost(uriBuilder.build()); post.setEntity(new StringEntity(jsonObject.toString(), ContentType.APPLICATION_JSON)); logInfo("Executing " + post); HttpResponse response = client.execute(post); String responseString = EntityUtils.toString(response.getEntity()); logInfo("Got login response " + responseString); JSONObject jsonResponse = new JSONObject(responseString); Customer customer = new Customer(); customer.setId(jsonResponse.getLong("id")); customer.setAddress(jsonResponse.getString("address")); customer.setName(jsonResponse.getString("name")); //initialize an order jsonObject = new JSONObject().put("status", "Initial"); uriBuilder = getUriBuilder("customers", customer.getId(), "orders"); post = new HttpPost(uriBuilder.build()); post.setEntity(new StringEntity(jsonObject.toString(), ContentType.APPLICATION_JSON)); logInfo("Executing " + post); response = client.execute(post);/*from w ww .j a v a2 s. c o m*/ responseString = EntityUtils.toString(response.getEntity()); logInfo("Got response " + responseString); jsonResponse = new JSONObject(responseString); Long orderId = jsonResponse.getLong("id"); // get an item uriBuilder = getUriBuilder("products"); uriBuilder.addParameter("featured", ""); HttpGet get = new HttpGet(uriBuilder.build()); logInfo("Executing " + get); response = client.execute(get); responseString = EntityUtils.toString(response.getEntity()); logInfo("Got response " + responseString); JSONArray jsonArray = new JSONArray(responseString); List<Map<String, Object>> products = Utils.getList(jsonArray); logInfo("array info " + Arrays.toString(products.toArray())); Map<String, Object> item = products.get(0); // put item on order jsonObject = new JSONObject().put("sku", item.get("sku")).put("quantity", 1); uriBuilder = getUriBuilder("customers", customer.getId(), "orders", orderId, "orderItems"); post = new HttpPost(uriBuilder.build()); post.setEntity(new StringEntity(jsonObject.toString(), ContentType.APPLICATION_JSON)); logInfo("Executing " + post); response = client.execute(post); responseString = EntityUtils.toString(response.getEntity()); logInfo("Got response " + responseString); // billing/process jsonObject = new JSONObject().put("amount", item.get("price")).put("creditCardNumber", 1234567890123456L) .put("expMonth", 1).put("expYear", 2019).put("verificationCode", 123) .put("billingAddress", customer.getAddress()).put("customerName", customer.getName()) .put("customerId", customer.getId()).put("orderNumber", orderId); logInfo(jsonObject.toString()); uriBuilder = getUriBuilder("billing", "process"); post = new HttpPost(uriBuilder.build()); post.setEntity(new StringEntity(jsonObject.toString(), ContentType.APPLICATION_JSON)); logInfo("Executing " + post); response = new DefaultHttpClient().execute(post); responseString = EntityUtils.toString(response.getEntity()); logInfo("Transaction processed as: " + responseString); return new JSONObject(responseString); }
From source file:de.freegroup.twogo.plotter.rpc.Client.java
public JSONObject sendAndReceive(String endpoint, String method, Object[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); RequestConfig config = RequestConfig.custom() // .setProxy(proxy) .build();//from w ww . j a v a 2 s . c o m HttpPost request = new HttpPost(this.serverUrl + endpoint); request.setConfig(config); request.setHeader("Content-Type", "application/json"); request.setHeader("X-CSRF-Token", getToken(httpclient)); JSONObject message = buildParam(method, args); StringEntity body = new StringEntity(message.toString(), ContentType.create("application/json", Consts.UTF_8)); request.setEntity(body); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); try { CloseableHttpResponse response = httpclient.execute(request); JSONTokener tokener = new JSONTokener(new BasicResponseHandler().handleResponse(response)); Object rawResponseMessage = tokener.nextValue(); JSONObject responseMessage = (JSONObject) rawResponseMessage; if (responseMessage == null) { throw new ClientError("Invalid response type - " + rawResponseMessage.getClass()); } return responseMessage; } catch (Exception e) { throw new ClientError(e); } }
From source file:foodcenter.android.service.AndroidRequestTransport.java
@Override public void send(String payload, TransportReceiver receiver) { HttpPost post = new HttpPost(); post.setHeader("Content-Type", "application/json;charset=UTF-8"); if (null != cookie) { post.setHeader("Cookie", cookie); }/*from w w w . j av a 2s. c o m*/ post.setURI(uri); 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) { Log.e(TAG, "UnsupportedEncodingException", e); ex = e; } catch (ClientProtocolException e) { Log.e(TAG, "ClientProtocolException", e); ex = e; } catch (IOException e) { Log.e(TAG, "IOException", e); ex = e; } catch (Exception e) { Log.e(TAG, "Exception", e); ex = e; } receiver.onTransportFailure(new ServerFailure(ex.getMessage())); }
From source file:com.sematext.ag.solr.sink.SimpleXMLDataSolrSink.java
/** * (non-Javadoc)//from www . j ava 2s .co m * * @see com.sematext.ag.sink.Sink#write(com.sematext.ag.Event) */ @Override public boolean write(SimpleDataEvent event) { LOG.info("Sending data to Apache Solr"); HttpPost postMethod = new HttpPost(solrUrl); postMethod.setHeader("Content-type", "application/xml"); StringEntity postEntity; try { postEntity = new StringEntity(XMLUtils.getSolrAddDocument(event.pairs()), "UTF-8"); postMethod.setEntity(postEntity); return execute(postMethod); } catch (UnsupportedEncodingException uee) { LOG.error("Error sending event: " + uee); return false; } }
From source file:org.talend.dataprep.command.preparation.UpdateStepRowMetadata.java
private HttpRequestBase onExecute(String preparationId, List<Step> steps) { try {//w w w . j a v a2 s . co m final String stepsAsJson = objectMapper.writeValueAsString(steps); final HttpPut updater = new HttpPut( preparationServiceUrl + "/preparations/" + preparationId + "/steps"); updater.setHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE); updater.setEntity(new StringEntity(stepsAsJson, APPLICATION_JSON)); return updater; } catch (JsonProcessingException e) { throw new TDPException(UNEXPECTED_EXCEPTION, e); } }
From source file:neembuu.httpserver.VFSHandler.java
@Override public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) { throw new MethodNotSupportedException(method + " method not supported"); }//from w w w . j a v a 2s .c o m String target = request.getRequestLine().getUri(); if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] entityContent = EntityUtils.toByteArray(entity); System.out.println("Incoming entity content (bytes): " + entityContent.length); } String filePath = URLDecoder.decode(target, "UTF-8"); FileAttributesProvider fap = fs.open(filePath.split("/")); if (fap == null) { response.setStatusCode(HttpStatus.SC_NOT_FOUND); StringEntity entity = new StringEntity( "<html><body><h1>File" + filePath + " not found</h1></body></html>", ContentType.create("text/html", "UTF-8")); response.setEntity(entity); System.out.println("File " + filePath + " not found"); } else if (fap.getFileType() != FileType.FILE || !(fap instanceof AbstractFile)) { response.setStatusCode(HttpStatus.SC_FORBIDDEN); StringEntity entity = new StringEntity("<html><body><h1>Access denied</h1></body></html>", ContentType.create("text/html", "UTF-8")); response.setEntity(entity); System.out.println("Cannot read file " + filePath + " fap=" + fap); } else { long offset = Utils.standardOffsetResponse(request, response, fap.getFileSize()); response.setStatusCode(HttpStatus.SC_OK); VFileEntity body = new VFileEntity((AbstractFile) fap, offset); response.setEntity(body); System.out.println("Serving file " + filePath); } }