List of usage examples for org.apache.http.entity StringEntity setContentEncoding
public void setContentEncoding(Header header)
From source file:edu.pdx.its.portal.routelandia.ApiPoster.java
public JSONObject postJsonObjectToUrl(String url, JSONObject jsonObject, APIResultWrapper retVal) { InputStream inputStream = null; String result = ""; try {//from w w w .j a v a 2 s .c o m // 1. create HttpClient HttpClient httpclient = new DefaultHttpClient(); // 2. make POST request to the given URL //http://capstoneaa.cs.pdx.edu/api/trafficstats HttpPost httpPost = new HttpPost(url); // 4. convert JSONObject to JSON to String String json = jsonObject.toString(); // 5. set json to StringEntity StringEntity se = new StringEntity(json); se.setContentType("application/json;charset=UTF-8"); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8")); // 6. set httpPost Entity httpPost.setEntity(se); // 7. Set some headers to inform server about the type of the content // httpPost.setHeader("Accept", "application/json"); // httpPost.setHeader("Content-type", "application/json"); // 8. Execute POST request to the given URL HttpResponse httpResponse = httpclient.execute(httpPost); // Make sure we've got a good response from the API. int status = httpResponse.getStatusLine().getStatusCode(); retVal.setHttpStatus(status); result = EntityUtils.toString(httpResponse.getEntity()); //Log.i("RAW HTTP RESULT", result); retVal.setRawResponse(result); } catch (Exception e) { Log.e("InputStream", e.getLocalizedMessage()); } try { Object json = new JSONTokener(result).nextValue(); if (json instanceof JSONObject) { retVal.setParsedResponse((JSONObject) json); return (JSONObject) json; } } catch (JSONException e) { e.printStackTrace(); } // If we got this far, we got something very wrong... Log.e(TAG, "Didn't get a valid JSON response!"); return null; }
From source file:HttpClient.HttpCalendarClient.java
private JSONObject send_request_response(JSONObject req, String operation) { //oggetto da rimpire e restituire JSONObject res = null;/*from w w w .j a va 2 s. c o m*/ //imposto il "contenitore" della risposta JSON CloseableHttpResponse response1 = null; //creo una richiesta di tipo POSTal WS HttpPost r_post = new HttpPost(url + operation); //imposto l'HEADER della richiesta a JSON r_post.addHeader(new BasicHeader("Content-Type", "application/json")); //Creo l'entita' da inserire nella richiesta, ipostandone come contenuto il JSON StringEntity param = new StringEntity(req.toJSONString(), "UTF8"); param.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); r_post.setEntity(param); //EFFETTUO LA RICHIESTA try { //EFFETTUO la richiesta ed attendo la risposta dal WS response1 = httpclient.execute(r_post); if (response1.getEntity() != null) //converto lo stream ottenuto in un oggetto JSON { res = convertStreamToJson(response1.getEntity().getContent()); } } catch (IOException ex) { Logger.getLogger(HttpCalendarClient.class.getName()).log(Level.SEVERE, null, ex); } finally { try { response1.close(); } catch (IOException ex) { Logger.getLogger(HttpCalendarClient.class.getName()).log(Level.SEVERE, null, ex); } } return res; }
From source file:HttpClient.HttpCalendarClient.java
private String send_request(JSONObject req, String operation) { String success = null;//from w ww . j a v a2 s . c o m //imposto il "contenitore" della risposta JSON CloseableHttpResponse response1 = null; //creo una richiesta di tipo POSTal WS HttpPost r_post = new HttpPost(url + operation); //imposto l'HEADER della richiesta a JSON r_post.addHeader(new BasicHeader("Content-Type", "application/json")); //Creo l'entita' da inserire nella richiesta, ipostandone come contenuto il JSON StringEntity param = new StringEntity(req.toJSONString(), "UTF8"); param.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); r_post.setEntity(param); //EFFETTUO LA RICHIESTA try { //EFFETTUO la richiesta ed attendo la risposta dal WS response1 = httpclient.execute(r_post); if (response1.getEntity() != null) { //converto lo stream ottenuto in un oggetto JSON JSONObject risposta = convertStreamToJson(response1.getEntity().getContent()); if (risposta != null) { String result = (String) risposta.get("code"); if (result.equalsIgnoreCase("201")) { success = (String) risposta.get("id"); } } } } catch (IOException ex) { Logger.getLogger(HttpCalendarClient.class.getName()).log(Level.SEVERE, null, ex); } finally { try { response1.close(); } catch (IOException ex) { Logger.getLogger(HttpCalendarClient.class.getName()).log(Level.SEVERE, null, ex); } } return success; }
From source file:net.gromgull.android.bibsonomyposter.BibsonomyPosterActivity.java
public void bookmark(String url, String title) throws ClientProtocolException, IOException { CredentialsProvider credProvider = new BasicCredentialsProvider(); credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), new UsernamePasswordCredentials(username, apikey)); StringWriter sw = new StringWriter(); XmlSerializer x = Xml.newSerializer(); x.setOutput(sw);/*w w w. j a v a 2s .co m*/ x.startDocument(null, null); x.startTag(null, "bibsonomy"); x.startTag(null, "post"); x.attribute(null, "description", "a bookmark"); x.startTag(null, "user"); x.attribute(null, "name", username); x.endTag(null, "user"); x.startTag(null, "tag"); x.attribute(null, "name", "from_android"); x.endTag(null, "tag"); x.startTag(null, "group"); x.attribute(null, "name", "public"); x.endTag(null, "group"); x.startTag(null, "bookmark"); x.attribute(null, "url", url); x.attribute(null, "title", title); x.endTag(null, "bookmark"); x.endTag(null, "post"); x.endTag(null, "bibsonomy"); x.endDocument(); Log.v(LOGTAG, "XML: " + sw.toString()); HttpPost httppost = new HttpPost("http://www.bibsonomy.org/api/users/" + username + "/posts"); StringEntity e = new StringEntity(sw.toString()); e.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/xml")); httppost.setEntity(e); DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.setCredentialsProvider(credProvider); HttpResponse response = httpclient.execute(httppost); Log.i(LOGTAG, "Bibsonomy said :" + response.getStatusLine()); if (response.getStatusLine().getStatusCode() != 201) { HttpEntity re = response.getEntity(); byte b[] = new byte[(int) re.getContentLength()]; re.getContent().read(b); Log.v(LOGTAG, "Bibsonomy said: " + new String(b)); throw new IOException("Bibsonomy said :" + response.getStatusLine()); } }
From source file:com.dalaran.async.task.http.AbstractHTTPService.java
protected String callPostRemoteService(String url, String json) throws IOException { SchemeRegistry schReg = new SchemeRegistry(); schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 2008)); HttpPost httpPost = new HttpPost(url); StringEntity se = new StringEntity(json); se.setContentEncoding(HTTP.UTF_8); // httpPost.setHeader(HTTP.USER_AGENT, URLs.USER_AGENT); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json"); SingleClientConnManager cm = new SingleClientConnManager(httpPost.getParams(), schReg); httpPost.setEntity(se);/*from w ww . j a va 2 s. c o m*/ HttpClient client = new DefaultHttpClient(); HttpResponse response = null; try { response = client.execute(httpPost); HttpEntity entity = response.getEntity(); return responseToBuffer(client, entity); } catch (Exception e) { return null; } }
From source file:com.osamashabrez.clientserver.json.ClientServerJSONActivity.java
/** Called when the activity is first created. */ @Override//from w w w.j a v a 2 s . c o m public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); buildref = (EditText) findViewById(R.id.editTextbuild); buildref.setFocusable(false); buildref.setClickable(false); recvdref = (EditText) findViewById(R.id.editTextrecvd); recvdref.setFocusable(false); recvdref.setClickable(false); JSONObject jsonobj; // declared locally so that it destroys after serving its purpose jsonobj = new JSONObject(); try { // adding some keys jsonobj.put("key", "value"); jsonobj.put("weburl", "hashincludetechnology.com"); // lets add some headers (nested headers) JSONObject header = new JSONObject(); header.put("devicemodel", android.os.Build.MODEL); // Device model header.put("deviceVersion", android.os.Build.VERSION.RELEASE); // Device OS version header.put("language", Locale.getDefault().getISO3Language()); // Language jsonobj.put("header", header); // Display the contents of the JSON objects buildref.setText(jsonobj.toString(2)); } catch (JSONException ex) { buildref.setText("Error Occurred while building JSON"); ex.printStackTrace(); } // Now lets begin with the server part try { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppostreq = new HttpPost(wurl); StringEntity se = new StringEntity(jsonobj.toString()); //se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); se.setContentType("application/json;charset=UTF-8"); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8")); httppostreq.setEntity(se); // httppostreq.setHeader("Accept", "application/json"); // httppostreq.setHeader("Content-type", "application/json"); // httppostreq.setHeader("User-Agent", "android"); HttpResponse httpresponse = httpclient.execute(httppostreq); HttpEntity resultentity = httpresponse.getEntity(); if (resultentity != null) { InputStream inputstream = resultentity.getContent(); Header contentencoding = httpresponse.getFirstHeader("Content-Encoding"); if (contentencoding != null && contentencoding.getValue().equalsIgnoreCase("gzip")) { inputstream = new GZIPInputStream(inputstream); } String resultstring = convertStreamToString(inputstream); inputstream.close(); resultstring = resultstring.substring(1, resultstring.length() - 1); recvdref.setText(resultstring + "\n\n" + httppostreq.toString().getBytes()); // JSONObject recvdjson = new JSONObject(resultstring); // recvdref.setText(recvdjson.toString(2)); } } catch (Exception e) { recvdref.setText("Error Occurred while processing JSON"); recvdref.setText(e.getMessage()); } }
From source file:com.globalsight.everest.workflowmanager.WfStatePostThread.java
private void doPost(WorkflowStatePosts wfStatePost, JSONObject message) { int num = wfStatePost.getRetryNumber(); CloseableHttpClient httpClient = getHttpClient(); for (int i = 0; i < num; i++) { try {/*from www.jav a 2 s . c o m*/ String listenerUrl = wfStatePost.getListenerURL(); String secretKey = wfStatePost.getSecretKey(); HttpPost httpPost = new HttpPost(listenerUrl); httpPost.setHeader(HttpHeaders.AUTHORIZATION, secretKey); RequestConfig config = RequestConfig.custom() .setConnectionRequestTimeout(wfStatePost.getTimeoutPeriod() * 1000) .setConnectTimeout(wfStatePost.getTimeoutPeriod() * 1000) .setSocketTimeout(wfStatePost.getTimeoutPeriod() * 1000).build(); httpPost.setConfig(config); StringEntity reqEntity = new StringEntity(message.toString()); reqEntity.setContentEncoding("UTF-8"); reqEntity.setContentType("application/json"); httpPost.setEntity(reqEntity); HttpResponse response = null; try { response = httpClient.execute(httpPost); } catch (Exception e) { s_logger.error("Post workflow transition info error:", e); } finally { if (response != null) { EntityUtils.consumeQuietly(response.getEntity()); } } if (response != null) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 204) { break; } else { logPostFailureInfo(statusCode); if (StringUtils.isNotEmpty(wfStatePost.getNotifyEmail()) && (i == num)) { String recipient = wfStatePost.getNotifyEmail(); long companyId = wfStatePost.getCompanyId(); String[] messageArguments = { wfStatePost.getName(), wfStatePost.getListenerURL(), message.toString() }; ServerProxy.getMailer().sendMailFromAdmin(recipient, messageArguments, MailerConstants.WORKFLOW_STATE_POST_FAILURE_SUBJECT, MailerConstants.WORKFLOW_STATE_POST_FAILURE_MESSAGE, String.valueOf(companyId)); } } } } catch (Exception e) { s_logger.error(e); } } }
From source file:de.topicmapslab.couchtm.internal.utils.SysDB.java
/** * Insertion of a topic map construct in the database. * /*www .j a va 2 s . c o m*/ * @param query Query to be executed * @param entity topic map construct to be put in the database * @return str Resultstring */ protected String putMethod(String query, String entity) { String responseBody = "{}"; try { put = new HttpPut("http://" + url + ":" + port + "/" + query); if (entity != null && entity.length() > 0) { StringEntity stringEntity = new StringEntity(entity, "UTF-8"); stringEntity.setContentEncoding("application/json"); put.setEntity(stringEntity); } //System.out.println("query: "+query); //System.out.println("entity "+entity); responseBody = client.execute(put, responseHandler); } catch (Exception e) { //System.out.println(put.getRequestLine()); e.printStackTrace(); } return responseBody; }
From source file:com.google.resting.method.post.PostServiceContext.java
private HttpEntity setMessageEntity(String message, EncodingTypes encoding, ContentType contentType) { StringEntity entity = null; try {/*from ww w. ja v a 2 s . co m*/ try { entity = new StringEntity(message); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (encoding != null) entity.setContentEncoding(encoding.getName()); if (contentType != null) entity.setContentType(contentType.getName()); } catch (Exception e) { e.printStackTrace(); } return entity; }
From source file:com.subgraph.vega.ui.httpviewer.entity.HttpEntityTextViewer.java
private HttpEntity createEntityForDocument(IDocument document) { try {/*from w w w . j a v a2s . c o m*/ final StringEntity entity = new StringEntity(document.get()); if (currentContentType != null && !currentContentType.isEmpty()) { entity.setContentType(currentContentType); } if (currentContentEncoding != null && !currentContentEncoding.isEmpty()) { entity.setContentEncoding(currentContentEncoding); } return entity; } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("Failed to create entity from document", e); } }