List of usage examples for org.apache.http.entity StringEntity StringEntity
public StringEntity(String str) throws UnsupportedEncodingException
From source file:org.wso2.carbon.esb.endpoint.test.ESBJAVA5017DroppedPayloadInFailoverLoadBalanceEndpoint.java
@Test(groups = "wso2.esb", description = "Test sending request to LoadBalancing Endpoint with application/json content type", enabled = false) public void testHTTPPostRequestJSONLoadBalanceEPScenario() throws Exception { String JSON_PAYLOAD = "{\"action\":\"ping\"}"; DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(getProxyServiceURLHttp("LBProxy")); StringEntity postingString = new StringEntity(JSON_PAYLOAD); httppost.setEntity(postingString);// w w w.j a v a2s . c om httppost.setHeader(HTTPConstants.CONTENT_TYPE, HTTPConstants.MEDIA_TYPE_APPLICATION_JSON); try { HttpResponse httpResponse = httpclient.execute(httppost); HttpEntity entity = httpResponse.getEntity(); BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent())); String result = ""; String line; while ((line = rd.readLine()) != null) { result += line; } Assert.assertTrue(result.contains("pong"), "Response doesn't contains the desired phrase."); } finally { httpclient.clearRequestInterceptors(); } }
From source file:gov.nih.nci.caxchange.messaging.RegisterConsentIntegrationTest.java
/** * Testcase for registerConsents flow// w w w . j a v a2 s.co m */ @Test public void registerConsents() { try { // Create the Specimen for which Consent has to be registered. createSpecimen(); final HttpPost httppost = new HttpPost(transcendCaxchangeServiceUrl); final StringEntity reqentity = new StringEntity(getRegisterConsentXMLStr()); httppost.setEntity(reqentity); httppost.setHeader(HttpHeaders.CONTENT_TYPE, XMLTEXT); final HttpResponse response = httpclient.execute(httppost); final HttpEntity entity = response.getEntity(); String createdXML = null; if (entity != null) { createdXML = EntityUtils.toString(entity); Assert.assertEquals(true, createdXML.contains("<responseStatus>SUCCESS</responseStatus>")); } } catch (ClientProtocolException e) { Assert.fail(e.getMessage()); } catch (IllegalStateException e) { Assert.fail(e.getMessage()); } catch (IOException e) { Assert.fail(e.getMessage()); } }
From source file:co.edu.uniajc.vtf.utils.RestAsyncTask.java
@Override protected String doInBackground(String... params) { String lsResult = ""; try {//from w w w.ja v a 2 s .com if (params[0].equals("0")) { HttpGet loRequest = new HttpGet(params[1].toString()); HttpResponse loResponse = coClient.execute(loRequest); lsResult = EntityUtils.toString(loResponse.getEntity()); } else if (params[0].equals("1")) { HttpPost loRequest = new HttpPost(params[1].toString()); StringEntity lsData = new StringEntity(params[2].toString()); loRequest.setEntity(lsData); loRequest.setHeader("Accept", "application/json"); loRequest.setHeader("Content-type", "application/json"); HttpResponse loResponse = coClient.execute(loRequest); lsResult = EntityUtils.toString(loResponse.getEntity()); } } catch (SocketTimeoutException ex) { this.cbohasError = true; lsResult = "Timeout exception"; } catch (Exception ex) { this.cbohasError = true; lsResult = ex.getMessage(); } return lsResult; }
From source file:com.anitech.resting.http.request.RequestDataMassager.java
private static StringEntity massageJSONData(Object inputData) throws RestingException { logger.debug("Inside massageJSONData!"); StringEntity stringEntity = null;//from ww w.ja v a2 s. c o m if (inputData instanceof Map<?, ?>) { try { logger.debug("Map>" + new JSONObject((Map<?, ?>) inputData).toJSONString()); stringEntity = new StringEntity(new JSONObject((Map<?, ?>) inputData).toJSONString()); } catch (UnsupportedEncodingException e) { throw new RestingException(e); } } else if (inputData instanceof String) { logger.debug("String>" + inputData); try { stringEntity = new StringEntity((String) inputData); } catch (UnsupportedEncodingException e) { throw new RestingException(e); } } else if (inputData instanceof StringBuffer || inputData instanceof StringBuilder) { logger.debug("String Buffer/Builder>" + inputData.toString()); try { stringEntity = new StringEntity((String) inputData.toString()); } catch (UnsupportedEncodingException e) { throw new RestingException(e); } } else if (inputData instanceof File) { try { logger.debug("File>" + new String(Files.readAllBytes(((File) inputData).toPath()), Charset.defaultCharset())); byte[] bytes = Files.readAllBytes(((File) inputData).toPath()); stringEntity = new StringEntity(new String(bytes, Charset.defaultCharset())); } catch (IOException e) { throw new RestingException(e); } } else if (inputData instanceof InputStream) { InputStream inputStream = ((InputStream) inputData); try { byte[] buffer = new byte[inputStream.available()]; int length = inputStream.read(buffer); logger.debug("InputStream>" + new String(buffer, 0, length, Charset.defaultCharset())); stringEntity = new StringEntity(new String(buffer, 0, length, Charset.defaultCharset())); } catch (IOException e) { throw new RestingException(e); } finally { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } else { logger.error("Unparseable data format found in inputs!"); throw new RestingException("Unparseable data format found in inputs!"); } return stringEntity; }
From source file:main.java.com.surevine.rssimporter.connection.BuddycloudClient.java
public String createPost(String channel, String node, String content) throws IOException { StringEntity post = new StringEntity("<entry xmlns=\"http://www.w3.org/2005/Atom\"><content>" + StringEscapeUtils.escapeXml(content) + "</content></entry>"); HttpPost httpPost = new HttpPost(host + "/" + channel + "/content/" + node); httpPost.setEntity(post);/*w w w. j a v a 2 s. c o m*/ HttpResponse response = this.execute(httpPost); if (response == null) { return null; } return "postid"; }
From source file:com.aregner.pandora.XmlRpc.java
@SuppressWarnings("unchecked") public Object callWithBody(String url, String body) throws XMLRPCException { postMethod.setURI(URI.create(url)); try {//from w w w.j av a 2s . com // set POST body HttpEntity entity = new StringEntity(body); postMethod.setEntity(entity); //Log.d(Tag.LOG, "ros HTTP POST"); // execute HTTP POST request HttpResponse response = client.execute(postMethod); //Log.d(Tag.LOG, "ros HTTP POSTed"); // check status code int statusCode = response.getStatusLine().getStatusCode(); //Log.d(Tag.LOG, "ros status code:" + statusCode); if (statusCode != HttpStatus.SC_OK) { throw new XMLRPCException("HTTP status code: " + statusCode + " != " + HttpStatus.SC_OK); } // parse response stuff // // setup pull parser XmlPullParser pullParser = XmlPullParserFactory.newInstance().newPullParser(); entity = response.getEntity(); Reader reader = new InputStreamReader(new BufferedInputStream(entity.getContent())); // for testing purposes only // reader = new StringReader("<?xml version='1.0'?><methodResponse><params><param><value>\n\n\n</value></param></params></methodResponse>"); pullParser.setInput(reader); // lets start pulling... pullParser.nextTag(); pullParser.require(XmlPullParser.START_TAG, null, Tag.METHOD_RESPONSE); pullParser.nextTag(); // either Tag.PARAMS (<params>) or Tag.FAULT (<fault>) String tag = pullParser.getName(); if (tag.equals(Tag.PARAMS)) { // normal response pullParser.nextTag(); // Tag.PARAM (<param>) pullParser.require(XmlPullParser.START_TAG, null, Tag.PARAM); pullParser.nextTag(); // Tag.VALUE (<value>) // no parser.require() here since its called in XMLRPCSerializer.deserialize() below // deserialize result Object obj = iXMLRPCSerializer.deserialize(pullParser); entity.consumeContent(); return obj; } else if (tag.equals(Tag.FAULT)) { // fault response pullParser.nextTag(); // Tag.VALUE (<value>) // no parser.require() here since its called in XMLRPCSerializer.deserialize() below // deserialize fault result Map<String, Object> map = (Map<String, Object>) iXMLRPCSerializer.deserialize(pullParser); String faultString = (String) map.get(Tag.FAULT_STRING); int faultCode = (Integer) map.get(Tag.FAULT_CODE); entity.consumeContent(); throw new XMLRPCFault(faultString, faultCode); } else { entity.consumeContent(); throw new XMLRPCException( "Bad tag <" + tag + "> in XMLRPC response - neither <params> nor <fault>"); } } catch (XMLRPCException e) { e.printStackTrace(); // catch & propagate XMLRPCException/XMLRPCFault throw e; } catch (Exception e) { e.printStackTrace(); // wrap any other Exception(s) around XMLRPCException throw new XMLRPCException(e); } }
From source file:org.jboss.aerogear.unifiedpush.quickstart.util.WebClient.java
public boolean register(User user) { try {// w ww .j av a2 s.c o m String registerURL = Constants.BASE_URL + "/rest/security/registration"; HttpPost post = new HttpPost(registerURL); post.setEntity(new StringEntity(new Gson().toJson(user))); post.setHeader("Accept", "application/json"); post.setHeader("Content-type", "application/json"); httpClient.execute(post); return true; } catch (Exception e) { Log.e(TAG, e.getMessage()); return false; } }
From source file:at.ac.tuwien.dsg.cloudlyra.utils.RestfulWSClient.java
public void callPutMethod(String xmlString) { try {/*from ww w . j a va 2s. c o m*/ //HttpGet method = new HttpGet(url); StringEntity inputKeyspace = new StringEntity(xmlString); Logger.getLogger(RestfulWSClient.class.getName()).log(Level.INFO, "Connection .. " + url); HttpPut request = new HttpPut(url); request.addHeader("content-type", "application/xml; charset=utf-8"); request.addHeader("Accept", "application/xml, multipart/related"); request.setEntity(inputKeyspace); HttpResponse methodResponse = this.getHttpClient().execute(request); int statusCode = methodResponse.getStatusLine().getStatusCode(); Logger.getLogger(RestfulWSClient.class.getName()).log(Level.INFO, "Status Code: " + statusCode); BufferedReader rd = new BufferedReader(new InputStreamReader(methodResponse.getEntity().getContent())); StringBuilder result = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { result.append(line); } // System.out.println("Response String: " + result.toString()); } catch (Exception ex) { } }
From source file:fr.julienvermet.bugdroid.util.NetworkUtils.java
public static NetworkResult postJson(String url, JSONObject data) { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); int statusCode = 0; try {// ww w .j ava2 s . c o m StringEntity se = new StringEntity(data.toString()); httpPost.setEntity(se); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); HttpResponse response = client.execute(httpPost); StatusLine statusLine = response.getStatusLine(); statusCode = statusLine.getStatusCode(); // if (statusCode == 201) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } reader.close(); // } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } return new NetworkResult(statusCode, builder.toString()); }
From source file:bigbluej.CrawlerTest.java
@Test public void shouldPost() throws IOException { String expectedResult = "break-out-prison"; when(httpClientFactory.create()).thenReturn(httpClient); HttpResponse httpResponse = new BasicHttpResponse( new BasicStatusLine(new ProtocolVersion("http", 100, 1), 200, "")); httpResponse.setEntity(new StringEntity(expectedResult)); when(httpClient.execute((HttpUriRequest) anyObject())).thenReturn(httpResponse); assertEquals(expectedResult, crawler.post("the-url")); }