List of usage examples for org.apache.http.entity StringEntity setContentType
public void setContentType(Header header)
From source file:com.tellapart.taba.engine.DefaultClientEngine.java
/** * Flush all buffered Events to the remote end-point. */// w w w .j a v a2 s .c o m protected void flush() { if (bufferSize == 0) { return; } // Clear the existing buffer. Map<String, List<Event>> flushBuffer; synchronized (lock) { flushBuffer = buffer; buffer = new HashMap<>(); bufferSize = 0; } String body = Transport.encode(clientId, flushBuffer); HttpPost httpPost = new HttpPost(eventPostUrl); try { StringEntity entity; entity = new StringEntity(body); entity.setContentType("application/json"); httpPost.setEntity(entity); try (CloseableHttpResponse response = httpClient.execute(httpPost)) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { logger.error(String.format("Bad status code: %d", statusCode)); } } catch (IOException e) { logger.error("Error flushing Taba Client buffer", e); } } catch (UnsupportedEncodingException e) { logger.error("Error encoding Taba Client buffer", e); } }
From source file:diuf.unifr.ch.first.xwot.notifications.OpenNotificationBuilder.java
/** * Encode into xml the Open JAXB class//from ww w .j a v a2 s . com * * @see Open * @param client * @return instance of a StringEntity containg xml informations */ @Override public StringEntity jaxbToStringEntity(Client client) { StringEntity body = null; if (open == null || !open.equalsToOpen(oldOpen)) { setOpen(); } try { body = new StringEntity(jaxbToXml(Open.class, open)); body.setContentType("application/xml"); } catch (UnsupportedEncodingException ex) { logger.error("Unable to encode StringEntity", ex); } return body; }
From source file:org.socraticgrid.hl7.ucs.nifi.processor.SendSMS.java
private String sendSMS(String smsText, String smsNumber, String smsServerUrl, String smsServerKey, String smsReference, ServiceStatusController serviceStatusControllerService) throws Exception { StringBuffer result = new StringBuffer(); try {/*from w w w . j a v a 2 s .co m*/ HttpClient client = HttpClientBuilder.create().build(); if (smsServerUrl != null && !smsServerUrl.endsWith("/")) { smsServerUrl = smsServerUrl + "/"; } HttpPost post = new HttpPost(smsServerUrl + smsServerKey + "/" + smsNumber + "/Extended"); String input = "{\"MessageBody\":\"" + smsText + "\",\"Reference\": \"" + smsReference + "\"}"; StringEntity params = new StringEntity(input, "UTF-8"); params.setContentType("application/json; charset=UTF-8"); post.setEntity(params); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } if (response.getStatusLine().getStatusCode() >= 400 && response.getStatusLine().getStatusCode() <= 599) { serviceStatusControllerService.updateServiceStatus("SMS", Status.UNAVAILABLE); } else { serviceStatusControllerService.updateServiceStatus("SMS", Status.AVAILABLE); } } catch (Exception e) { serviceStatusControllerService.updateServiceStatus("SMS", Status.UNAVAILABLE); getLogger().error("Error occurred while sending SMS!", e); throw e; } return result.toString(); }
From source file:org.socraticgrid.hl7.ucs.nifi.processor.SendVOIPMessage.java
private String sendVoipMsg(String voipServerUrl, String voipServerToken, String voipMsgTextAttrVal, String voidMsgNumberAttrVal, ServiceStatusController serviceStatusControllerService) throws ClientProtocolException, IOException { String status = ""; try {//from ww w . ja v a 2 s .c o m HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(voipServerUrl); String input = "{\"token\":\"" + voipServerToken + "\",\"numberToDial\":\"" + voidMsgNumberAttrVal + "\",\"msg\":\"" + voipMsgTextAttrVal + "\"}"; StringEntity params = new StringEntity(input, "UTF-8"); params.setContentType("application/json; charset=UTF-8"); post.setEntity(params); HttpResponse response = client.execute(post); status = IOUtils.toString(response.getEntity().getContent()); if (response.getStatusLine().getStatusCode() >= 400 && response.getStatusLine().getStatusCode() <= 599) { serviceStatusControllerService.updateServiceStatus("VOIP", Status.UNAVAILABLE); } else { serviceStatusControllerService.updateServiceStatus("VOIP", Status.AVAILABLE); } } catch (Exception e) { serviceStatusControllerService.updateServiceStatus("VOIP", Status.UNAVAILABLE); getLogger().error("Error occurred while sending Voip Message!", e); throw e; } return status; }
From source file:org.apache.stratos.metadata.client.rest.DefaultRestClient.java
private void addStringPayload(HttpPost post, String payloadText) { if (org.apache.commons.lang.StringUtils.isEmpty(payloadText)) { throw new IllegalArgumentException("Payload text can not be null or empty"); }/*from ww w . j a v a2s. c o m*/ StringEntity stringEntity = null; try { stringEntity = new StringEntity(payloadText); stringEntity.setContentType(APPLICATION_JSON); } catch (UnsupportedEncodingException e) { String message = String.format("Could not add string to payload: [payload] %s", payloadText); log.error(message, e); } post.setEntity(stringEntity); }
From source file:org.apache.camel.component.cxf.jaxrs.CxfRsRouterTest.java
@Test public void testPostConsumerUniqueResponseCode() throws Exception { HttpPost post = new HttpPost("http://localhost:" + getPort() + "/CxfRsRouterTest/route/customerservice/customersUniqueResponseCode"); post.addHeader("Accept", "text/xml"); StringEntity entity = new StringEntity(POST_REQUEST, "ISO-8859-1"); entity.setContentType("text/xml; charset=ISO-8859-1"); post.setEntity(entity);//from w w w . j a va 2 s .c o m HttpClient httpclient = new DefaultHttpClient(); try { HttpResponse response = httpclient.execute(post); assertEquals(201, response.getStatusLine().getStatusCode()); assertEquals( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Customer><id>124</id><name>Jack</name></Customer>", EntityUtils.toString(response.getEntity())); HttpDelete del = new HttpDelete( "http://localhost:" + getPort() + "/CxfRsRouterTest/route/customerservice/customers/124/"); httpclient.execute(del); } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:org.apache.camel.itest.osgi.cxf.blueprint.CxfRsBlueprintRouterTest.java
@Test public void testPostConsumer() throws Exception { HttpPost post = new HttpPost("http://localhost:9000/route/customerservice/customers"); post.addHeader("Accept", "text/xml"); StringEntity entity = new StringEntity(POST_REQUEST, "ISO-8859-1"); entity.setContentType("text/xml; charset=ISO-8859-1"); post.setEntity(entity);/*from w w w . jav a 2 s .c o m*/ HttpClient httpclient = new DefaultHttpClient(); try { HttpResponse response = httpclient.execute(post); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Customer><id>124</id><name>Jack</name></Customer>", EntityUtils.toString(response.getEntity())); } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:co.cask.cdap.client.rest.handlers.StreamInfoHttpRequestHandler.java
@Override public void handle(HttpRequest httpRequest, HttpResponse response, HttpContext httpContext) throws HttpException, IOException { RequestLine requestLine = httpRequest.getRequestLine(); String method = requestLine.getMethod(); int statusCode; if (!HttpMethod.GET.equals(method)) { statusCode = HttpStatus.SC_NOT_IMPLEMENTED; } else {/* w w w.ja v a 2 s .c om*/ String uri = requestLine.getUri(); String streamName = TestUtils.getStreamNameFromUri(uri); if (TestUtils.AUTH_STREAM_NAME.equals(streamName)) { statusCode = TestUtils.authorize(httpRequest); } else if (streamName.contains(TestUtils.WRITER_TEST_STREAM_NAME_POSTFIX)) { statusCode = HttpStatus.SC_OK; } else { statusCode = TestUtils.getStatusCodeByStreamName(streamName); } if (statusCode == HttpStatus.SC_OK) { StringEntity entity = new StringEntity( "{\"partitionDuration\":3600000,\"indexInterval\":10000,\"ttl\":" + RestTest.STREAM_TTL + "}"); entity.setContentType(MediaType.APPLICATION_JSON); response.setEntity(entity); } } response.setStatusCode(statusCode); }
From source file:com.vmware.vchs.api.samples.services.Compute.java
/** * This method will attempt to deploy (or undeploy) the provided vApp. The Boolean provided * parameter, deploy, if set to true attempts to deploy the vApp, otherwise false will attempt * to undeploy the vApp./*from w ww. j a va 2s. c o m*/ * * @param vApp * @param deploy * @param version * @param token * @return */ public static final TaskType deployUndeployVM(VAppType vApp, Boolean deploy, String version, String token) { String deployHref = null; // Search the list of links for the vApp rel="deploy" to get the correct Href for (LinkType link : vApp.getLink()) { if (link.getRel().equalsIgnoreCase("deploy")) { deployHref = link.getHref(); break; } } // Only proceed if we found a valid deploy Href if (null != deployHref) { DeployVAppParamsType deployParams = new DeployVAppParamsType(); deployParams.setPowerOn(deploy); // Create the XSD generated ObjectFactory factory class ObjectFactory obj = new ObjectFactory(); // Create the DeployVAppParamsType from the ObjectFactory JAXBElement<DeployVAppParamsType> deployParamsType = obj.createDeployVAppParams(deployParams); // Get the StringEntity marshaled instance StringEntity se = HttpUtils.marshal(DeployVAppParamsType.class, deployParamsType); HttpPost deployPost = new HttpPost(deployHref); deployPost.setHeader(HttpHeaders.ACCEPT, SampleConstants.APPLICATION_PLUS_XML_VERSION + version + ";charset=utf-8"); deployPost.setHeader(HttpHeaders.AUTHORIZATION, token); // Set the Content-Type header for the VM vApp template parameters se.setContentType("application/vnd.vmware.vcloud.deployVAppParams+xml"); // Set it as the POST body deployPost.setEntity(se); // Invoke the HttoPost to initiate the VM creation process HttpResponse response = HttpUtils.httpInvoke(deployPost); // Make sure response status is 201 Created if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) { TaskType taskType = HttpUtils.unmarshal(response.getEntity(), TaskType.class); return taskType; } } return null; }
From source file:org.apache.camel.component.cxf.jaxrs.CxfRsRouterTest.java
@Test public void testPostConsumer() throws Exception { HttpPost post = new HttpPost( "http://localhost:" + getPort() + "/CxfRsRouterTest/route/customerservice/customers"); post.addHeader("Accept", "text/xml"); StringEntity entity = new StringEntity(POST_REQUEST, "ISO-8859-1"); entity.setContentType("text/xml; charset=ISO-8859-1"); post.setEntity(entity);// www . j a v a 2s .c o m HttpClient httpclient = new DefaultHttpClient(); try { HttpResponse response = httpclient.execute(post); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Customer><id>124</id><name>Jack</name></Customer>", EntityUtils.toString(response.getEntity())); HttpDelete del = new HttpDelete( "http://localhost:" + getPort() + "/CxfRsRouterTest/route/customerservice/customers/124/"); httpclient.execute(del); } finally { httpclient.getConnectionManager().shutdown(); } }