List of usage examples for org.apache.http.entity StringEntity setContentType
public void setContentType(Header header)
From source file:org.apache.camel.component.cxf.cxfbean.CxfBeanTest.java
@Test public void testJaxWsBean() throws Exception { HttpPost post = new HttpPost("http://localhost:" + PORT2 + "/customerservice/customers"); post.addHeader("Accept", "text/xml"); String body = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<soap:Body><GetPerson xmlns=\"http://camel.apache.org/wsdl-first/types\">" + "<personId>hello</personId></GetPerson></soap:Body></soap:Envelope>"; StringEntity entity = new StringEntity(body, "ISO-8859-1"); entity.setContentType("text/xml; charset=ISO-8859-1"); post.setEntity(entity);/*from www . j av a 2s .co m*/ HttpClient httpclient = new DefaultHttpClient(); try { HttpResponse response = httpclient.execute(post); assertEquals(200, response.getStatusLine().getStatusCode()); String responseBody = EntityUtils.toString(response.getEntity()); String correct = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body>" + "<GetPersonResponse xmlns=\"http://camel.apache.org/wsdl-first/types\">" + "<personId>hello</personId><ssn>000-000-0000</ssn><name>Bonjour</name></GetPersonResponse></soap:Body></soap:Envelope>"; assertEquals("Get a wrong response", correct, responseBody); } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:ua.kiev.doctorvera.utils.SMSGateway.java
@SuppressWarnings("deprecation") public ArrayList<String> send(String phone, String sms) { ArrayList<String> result = new ArrayList<String>(); final String MESSAGE = "<message><service id='single' source='" + FROM + "'/><to>" + phone + "</to><body content-type='text/plain'>" + sms + "</body></message>"; @SuppressWarnings("resource") HttpClient httpclient = new DefaultHttpClient(); String xml = null;/* w ww.j a v a2 s . com*/ try { HttpPost httpPost = new HttpPost(SMS_SEND_URL); StringEntity entity = new StringEntity(MESSAGE, "UTF-8"); entity.setContentType("text/xml"); entity.setChunked(true); httpPost.setEntity(entity); httpPost.addHeader( BasicScheme.authenticate(new UsernamePasswordCredentials(LOGIN, PASS), "UTF-8", false)); HttpResponse response = httpclient.execute(httpPost); HttpEntity resEntity = response.getEntity(); LOG.info("Sending SMS: " + (response.getStatusLine().getStatusCode() == 200)); xml = EntityUtils.toString(resEntity); } catch (Exception e) { LOG.severe("" + e.getStackTrace()); } finally { httpclient.getConnectionManager().shutdown(); } //parsing xml result Document doc = loadXMLFromString(xml); NodeList nl = doc.getElementsByTagName("status"); Element status = (Element) nl.item(0); result.add(0, status.getAttribute("id").toString()); //tracking id at position 0 result.add(1, status.getAttribute("date").toString()); //date at position 1 result.add(2, getElementValue(status.getFirstChild())); //state at position 2 return result; }
From source file:com.centonni.kpakpato.api.sms.OrangeSmsAPI.java
/** * This method should return the authorization that basically contain * the authorization token to acces the provider Api * @see AuthenticationToken/*from w w w.ja v a 2 s.c om*/ * @return */ AuthenticationToken getToken() { String clientInfos = clientId + ":" + clientSecret; String body = "grant_type=client_credentials"; AuthenticationToken authenticationToken = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(OrangeSmsAPI.BASE_URL + "/" + OrangeSmsAPI.TOKEN_URL); postRequest.setHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString(clientInfos.getBytes())); StringEntity input = new StringEntity(body); input.setContentType("application/x-www-form-urlencoded"); postRequest.setEntity(input); HttpResponse response = httpClient.execute(postRequest); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } final ObjectMapper objectMapper = new ObjectMapper(); authenticationToken = objectMapper.readValue(response.getEntity().getContent(), AuthenticationToken.class); } catch (JsonParseException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } return authenticationToken; }
From source file:org.apache.camel.component.cxf.cxfbean.CxfBeanTest.java
@Test public void testPostConsumer() throws Exception { HttpPost post = new HttpPost("http://localhost:" + PORT1 + "/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);/* ww w .j a va 2 s. c om*/ HttpClient httpclient = new DefaultHttpClient(); try { HttpResponse response = httpclient.execute(post); assertEquals(200, response.getStatusLine().getStatusCode()); String id = getCustomerId("Jack"); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Customer><id>" + id + "</id><name>Jack</name></Customer>", EntityUtils.toString(response.getEntity())); } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:metadata_crawler.Metadata.java
public void loadDatasetInformation(Dataset ds, String datasetid) throws Exception { HttpPost post = new HttpPost(DATAHUBSINGLEURL); post.setHeader("X-CKAN-API-Key", "bf317334-3107-4a25-9773-b5961ef3500b"); StringEntity input = new StringEntity("{\"id\":\"" + datasetid + "\"}"); input.setContentType("application/json"); post.setEntity(input);//from ww w .java2 s . c o m HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(post); String responsestr = getResponseText(response); JSONObject jsondataset = new JSONObject(responsestr).getJSONObject("result"); JSONArray jsondatasetres = jsondataset.getJSONArray("resources"); JSONArray jsondatasettags = jsondataset.getJSONArray("tags"); JSONArray jsondatasetgroups = jsondataset.getJSONArray("groups"); //load the dataset tags for (int i = 0; i < jsondatasettags.length(); i++) { JSONObject jsontmp = jsondatasettags.getJSONObject(i); if (!jsontmp.isNull("name")) { String strname = jsontmp.getString("name"); ds.tags.add(strname); } } //load the dataset groups for (int i = 0; i < jsondatasetgroups.length(); i++) { JSONObject jsontmp = jsondatasetgroups.getJSONObject(i); if (!jsontmp.isNull("name")) { String strname = jsontmp.getString("name"); ds.groups.add(strname); } } //load the SPARQL endpoint for (int i = 0; i < jsondatasetres.length(); i++) { JSONObject jsontmp = jsondatasetres.getJSONObject(i); String strname = "", strdesc = "", format = ""; if (!jsontmp.isNull("name")) { strname = jsontmp.getString("name"); } if (!jsontmp.isNull("description")) { strdesc = jsontmp.getString("description"); } if (!jsontmp.isNull("format")) { format = jsontmp.getString("format"); } if (strname.contains("SPARQL") || strdesc.contains("SPARQL") || format.contains("sparql")) { ds.url = jsontmp.getString("url"); } } }
From source file:org.apache.camel.component.cxf.cxfbean.CxfBeanTest.java
@Test public void testPostConsumerUniqueResponseCode() throws Exception { HttpPost post = new HttpPost("http://localhost:" + PORT1 + "/customerservice/customersUniqueResponseCode"); post.addHeader("Accept", "text/xml"); StringEntity entity = new StringEntity(POST2_REQUEST, "ISO-8859-1"); entity.setContentType("text/xml; charset=ISO-8859-1"); post.setEntity(entity);/*from w ww . j a v a 2 s . c om*/ HttpClient httpclient = new DefaultHttpClient(); try { HttpResponse response = httpclient.execute(post); assertEquals(201, response.getStatusLine().getStatusCode()); String id = getCustomerId("James"); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Customer><id>" + id + "</id><name>James</name></Customer>", EntityUtils.toString(response.getEntity())); } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:edu.mit.mobile.android.demomode.Preferences.java
private void fromCfgString(String cfg) { final Uri cfgUri = Uri.parse(cfg); if ("data".equals(cfgUri.getScheme())) { final String[] cfgParts = cfgUri.getEncodedSchemeSpecificPart().split(",", 2); if (CFG_MIME_TYPE.equals(cfgParts[0])) { final Editor ed = mPrefs.edit(); final ArrayList<ContentProviderOperation> cpos = new ArrayList<ContentProviderOperation>(); // first erase everything cpos.add(ContentProviderOperation.newDelete(LauncherItem.CONTENT_URI).build()); try { final StringEntity entity = new StringEntity(cfgParts[1]); entity.setContentType("application/x-www-form-urlencoded"); final List<NameValuePair> nvp = URLEncodedUtils.parse(entity); for (final NameValuePair pair : nvp) { final String name = pair.getName(); Log.d(TAG, "parsed pair: " + pair); if (CFG_K_SECRETKEY.equals(name)) { ed.putString(KEY_PASSWORD, pair.getValue()); } else if (CFG_K_APPS.equals(name)) { final String[] app = pair.getValue().split(CFG_PKG_SEP, 2); final ContentProviderOperation cpo = ContentProviderOperation .newInsert(LauncherItem.CONTENT_URI) .withValue(LauncherItem.PACKAGE_NAME, app[0]) .withValue(LauncherItem.ACTIVITY_NAME, app[1]).build(); cpos.add(cpo);//w w w . j av a 2 s .c o m Log.d(TAG, "adding " + cpo); } } ed.commit(); getContentResolver().applyBatch(HomescreenProvider.AUTHORITY, cpos); } catch (final UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final OperationApplicationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { Log.e(TAG, "unknown MIME type for data URI: " + cfgParts[0]); } } else { Log.e(TAG, "not a data URI"); } }
From source file:com.gitblit.plugin.glip.Glip.java
/** * Send a payload message.//w ww . j av a 2 s .com * * @param payload * @throws IOException */ public void send(Payload payload) throws IOException { String conversation = payload.getConversation(); String token; if (StringUtils.isEmpty(conversation)) { // default conversation token = runtimeManager.getSettings().getString(Plugin.SETTING_DEFAULT_TOKEN, null); } else { // specified conversation, validate token token = runtimeManager.getSettings() .getString(String.format(Plugin.SETTING_CONVERSATION_TOKEN, conversation), null); if (StringUtils.isEmpty(token)) { token = runtimeManager.getSettings().getString(Plugin.SETTING_DEFAULT_TOKEN, null); log.warn("No Glip API token specified for '{}', defaulting to default conversation'", payload.getConversation()); log.warn("Please set '{} = TOKEN' in gitblit.properties", String.format(Plugin.SETTING_CONVERSATION_TOKEN, conversation)); } } Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new GmtDateTypeAdapter()).create(); String json = gson.toJson(payload); log.debug(json); HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, 5000); client.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 5000); String conversationUrl = payload.getEndPoint(token); HttpPost post = new HttpPost(conversationUrl); post.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Constants.NAME + "/" + Constants.getVersion()); post.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); // post as JSON StringEntity entity = new StringEntity(json, "UTF-8"); entity.setContentType("application/json"); post.setEntity(entity); HttpResponse response = client.execute(post); int rc = response.getStatusLine().getStatusCode(); if (HttpStatus.SC_OK == rc) { // This is the expected result code // replace this with post.closeConnection() after JGit updates to HttpClient 4.2 post.abort(); } else { String result = null; InputStream is = response.getEntity().getContent(); try { byte[] buffer = new byte[8192]; ByteArrayOutputStream os = new ByteArrayOutputStream(); int len = 0; while ((len = is.read(buffer)) > -1) { os.write(buffer, 0, len); } result = os.toString("UTF-8"); } finally { if (is != null) { is.close(); } } log.error("Glip plugin sent:"); log.error(json); log.error("Glip returned:"); log.error(result); throw new IOException(String.format("Glip Error (%s): %s", rc, result)); } }
From source file:com.centonni.kpakpato.api.sms.OrangeSmsAPI.java
@Override public boolean sendSms(MessageContext message, String receiverAdress) { String receiver = "tel:+" + receiverAdress; String path = BASE_URL + "/" + "smsmessaging/v1/outbound/" + message.getSenderAdress() + "/requests"; String body = bodyToJSON(createMessageBody(message, receiver)); boolean state = false; try {//from w ww . j av a 2 s .c om DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(path); postRequest.setHeader("Authorization", token.getAuthorization()); StringEntity input = new StringEntity(body); input.setContentType("application/json"); postRequest.setEntity(input); HttpResponse response = httpClient.execute(postRequest); if (response.getStatusLine().getStatusCode() != 201) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } else { state = true; final ObjectMapper objectMapper = new ObjectMapper(); OutboundSMSMessageRequest messageBody = objectMapper.readValue(response.getEntity().getContent(), OutboundSMSMessageRequest.class); } } catch (JsonParseException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } return state; }
From source file:com.centonni.kpakpato.api.sms.OrangeSmsAPI.java
@Override public boolean sendSms(MessageContext message, String receiverAdress, String authorisationToken) { String receiver = "tel:+" + receiverAdress; String path = BASE_URL + "/" + "smsmessaging/v1/outbound/" + message.getSenderAdress() + "/requests"; String body = bodyToJSON(createMessageBody(message, receiver)); boolean state = false; try {//from w ww. ja v a2 s .c o m DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(path); postRequest.setHeader("Authorization", authorisationToken); StringEntity input = new StringEntity(body); input.setContentType("application/json"); postRequest.setEntity(input); HttpResponse response = httpClient.execute(postRequest); if (response.getStatusLine().getStatusCode() != 201) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } else { state = true; final ObjectMapper objectMapper = new ObjectMapper(); MessageBody messageBody = objectMapper.readValue(response.getEntity().getContent(), MessageBody.class); } } catch (JsonParseException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } return state; }