List of usage examples for org.apache.http.entity StringEntity setContentType
public void setContentType(Header header)
From source file:com.wegas.integration.IntegrationTest.java
/** * * @return//from w ww. j a va 2 s.c o m */ private String postJSON(String url, String jsonContent) throws IOException { HttpPost post = new HttpPost(baseURL + url); setHeaders(post); StringEntity strEntity = new StringEntity(jsonContent); strEntity.setContentType("application/json"); post.setEntity(strEntity); HttpResponse response = client.execute(post); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); return getEntityAsString(response.getEntity()); }
From source file:com.osamashabrez.clientserver.json.ClientServerJSONActivity.java
/** Called when the activity is first created. */ @Override/*w w w . j a v a2s. 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.example.android.donebar.DoneBarActivity.java
public void sendJSON(JSONObject obj) { StringEntity se = null; try {//from ww w . j a v a 2 s .c o m se = new StringEntity(obj.toString()); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); } catch (UnsupportedEncodingException e) { } AsyncHttpClient client = new AsyncHttpClient(); client.post(null, "http://192.168.0.101:8080/AndroidRESTful2/webresources/com.erikchenmelbourne.entities.caller", se, "application/json", new AsyncHttpResponseHandler() { private String string; @Override public void onSuccess(int statusCode, Header[] headers, byte[] response) { if (response != null) try { string = new String(response, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } else { Toast.makeText(getApplicationContext(), "Status Code: " + statusCode + " Data has been posted.", Toast.LENGTH_LONG) .show(); finish(); } /*try { JSONObject obj = new JSONObject(string); if (obj.getBoolean("status")) { setDefaultValues(); Toast.makeText(getApplicationContext(), "Information has been sent!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), obj.getString("error_msg"), Toast.LENGTH_LONG).show(); } } catch (JSONException e) { Toast.makeText(getApplicationContext(), "Error Occurred. [Server's JSON response is invalid]!", Toast.LENGTH_LONG).show(); e.printStackTrace(); }*/ } @Override public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) { if (i == 404) { Toast.makeText(getApplicationContext(), "Requested resource not found.", Toast.LENGTH_LONG).show(); } else if (i == 500) { Toast.makeText(getApplicationContext(), "Something went wrong at server end.", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Unexpected Error occurred. [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show(); } } }); }
From source file:com.yottaa.newrelic.PostJob.java
/** * @param params// ww w .ja v a 2s. c o m * @param apiKey * @param postedJSON * @return */ protected Object newrelicPost(JSONObject params, String apiKey, Object postedJSON) { Object responseObj = null; try { URIBuilder builder = new URIBuilder("https://platform-api.newrelic.com"); builder.setPath("/platform/v1/metrics"); if (params != null) { Iterator it = params.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); builder.setParameter(entry.getKey().toString(), entry.getValue().toString()); } } URI uri = builder.build(); HttpPost httpMethod = new HttpPost(uri); httpMethod.setHeader("X-License-Key", apiKey); httpMethod.removeHeaders("accept"); httpMethod.setHeader("Accept", "application/json"); StringEntity entity = new StringEntity(postedJSON.toString(), HTTP.UTF_8); entity.setContentType("application/json"); httpMethod.setEntity(entity); HttpClient client = new DefaultHttpClient(); HttpResponse httpResponse = client.execute(httpMethod); HttpEntity responseEntity = httpResponse.getEntity(); if (responseEntity != null) { String responseStr = EntityUtils.toString(responseEntity); JSONParser parser = new JSONParser(); responseObj = parser.parse(responseStr); } } catch (UnsupportedEncodingException e) { logger.error("Failed to post Yottaa metrics to New Relic", e); } catch (ClientProtocolException e) { logger.error("Failed to post Yottaa metrics to New Relic", e); } catch (IOException e) { logger.error("Failed to post Yottaa metrics to New Relic", e); } catch (URISyntaxException e) { logger.error("Failed to post Yottaa metrics to New Relic", e); } catch (ParseException e) { logger.error("Failed to post Yottaa metrics to New Relic", e); } return responseObj; }
From source file:org.freeeed.search.web.solr.SolrTagService.java
private Result sendUpdateCommand(String data) { SolrSessionObject solrSession = SessionContext.getSolrSession(); if (solrSession == null || solrSession.getSelectedCase() == null) { return Result.ERROR; }/* ww w. ja va 2s.c o m*/ String solrCore = solrSession.getSelectedCase().getSolrSourceCore(); String url = configuration.getSolrEndpoint() + "/solr/" + solrCore + "/update?commit=true"; log.debug("Will send request to: " + url + ", data: " + data); HttpClient httpClient = new DefaultHttpClient(); try { HttpPost request = new HttpPost(url); StringEntity params = new StringEntity(data); params.setContentType("application/json"); request.setEntity(params); HttpResponse response = httpClient.execute(request); response.getStatusLine().getStatusCode(); } catch (Exception ex) { log.error("Problem tagging: " + ex); return Result.ERROR; } return Result.SUCCESS; }
From source file:co.cask.cdap.client.rest.RestStreamClient.java
@Override public void setTTL(String stream, long ttl) throws IOException { HttpPut putRequest = new HttpPut(restClient.getBaseURL() .resolve(String.format("/%s/streams/%s/config", restClient.getVersion(), stream))); StringEntity entity = new StringEntity(GSON.toJson(ImmutableMap.of(TTL_ATTRIBUTE_NAME, ttl))); entity.setContentType(MediaType.APPLICATION_JSON); putRequest.setEntity(entity);//from ww w .j a v a2 s .c om CloseableHttpResponse httpResponse = restClient.execute(putRequest); try { int responseCode = httpResponse.getStatusLine().getStatusCode(); LOG.debug("Set TTL Response Code : {}", responseCode); RestClient.responseCodeAnalysis(httpResponse); } finally { httpResponse.close(); } }
From source file:com.openmeap.http.HttpRequestExecuterImpl.java
public HttpResponse postContent(String url, String content, String contentType) throws HttpRequestException { try {/*from w w w.j av a 2 s. c o m*/ StringEntity stringEntity = new StringEntity(content, FormConstants.CHAR_ENC_DEFAULT); stringEntity.setContentType(contentType); HttpPost httppost = new HttpPost(url); httppost.setHeader(FormConstants.CONTENT_TYPE, contentType); httppost.setEntity(stringEntity); return execute(httppost); } catch (Exception e) { throw new HttpRequestException(e); } }
From source file:ste.web.http.beanshell.BugFreeBeanShellUtils.java
@Test public void formUrlEncodedParameters() throws Exception { BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("get", TEST_URI09); StringEntity e = new StringEntity(TEST_QUERY_STRING); e.setContentType(ContentType.APPLICATION_FORM_URLENCODED.getMimeType()); request.setEntity(e);/*w w w . j a v a2s .com*/ HttpSessionContext context = new HttpSessionContext(); context.setAttribute(HttpCoreContext.HTTP_CONNECTION, getConnection()); request.addHeader(HTTP.CONTENT_TYPE, e.getContentType().getValue()); Interpreter i = new Interpreter(); BeanShellUtils.setup(i, request, RESPONSE_OK, context); then(i.get(TEST_URL_PARAM1)).isEqualTo(TEST_VALUE1); then(i.get(TEST_URL_PARAM2)).isEqualTo(TEST_VALUE2); e.setContentType(ContentType.APPLICATION_FORM_URLENCODED.getMimeType() + " ; charset=UTF-8"); request.setHeader(HTTP.CONTENT_TYPE, e.getContentType().getValue()); i = new Interpreter(); BeanShellUtils.setup(i, request, RESPONSE_OK, context); then(i.get(TEST_URL_PARAM1)).isEqualTo(TEST_VALUE1); then(i.get(TEST_URL_PARAM2)).isEqualTo(TEST_VALUE2); }
From source file:org.opendaylight.eman.impl.EmanSNMPBinding.java
public String getEoAttrSNMP(String deviceIP, String attribute) { LOG.info("EmanSNMPBinding.getEoAttrSNMP: "); /* To do: generalize targetURL research using Java binding to make reference to 'local' ODL API *//*from ww w . j ava 2s .co m*/ String targetUrl = "http://localhost:8181/restconf/operations/snmp:snmp-get"; String bodyString = buildSNMPGetBody(deviceIP, attribute); CloseableHttpClient httpClient = HttpClients.createDefault(); String result = null; try { /* invoke ODL SNMP API */ HttpPost httpPost = new HttpPost(targetUrl); httpPost.addHeader("Authorization", "Basic " + encodedAuthStr); StringEntity inputBody = new StringEntity(bodyString); inputBody.setContentType(CONTENTTYPE_JSON); httpPost.setEntity(inputBody); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity responseEntity = httpResponse.getEntity(); LOG.info("EmanSNMPBinding.getEoAttrSNMP: Response Status: " + httpResponse.getStatusLine().toString()); InputStream in = responseEntity.getContent(); /* Parse response from ODL SNMP API */ JsonReader rdr = Json.createReader(in); JsonObject obj = rdr.readObject(); JsonObject output = obj.getJsonObject("output"); JsonArray results = output.getJsonArray("results"); JsonObject pwr = results.getJsonObject(0); String oid = pwr.getString("oid"); result = pwr.getString("value"); rdr.close(); LOG.info("EmanSNMPBinding.getEoAttrSNMP: oid: " + oid + " value " + result); } catch (Exception ex) { LOG.info("Error: " + ex.getMessage(), ex); } finally { try { httpClient.close(); } catch (IOException ex) { LOG.info("Error: " + ex.getMessage(), ex); } } return (result); }
From source file:org.opendatakit.aggregate.externalservice.JsonServer.java
@Override protected void insertData(Submission submission, CallingContext cc) throws ODKExternalServiceException { try {/*from w w w. j av a 2s . c o m*/ BinaryOption option = objectEntity.getBinaryOption(); ByteArrayOutputStream baStream = new ByteArrayOutputStream(); PrintWriter pWriter = new PrintWriter(new OutputStreamWriter(baStream, HtmlConsts.UTF8_ENCODE)); System.out.println("Sending one JSON Submission"); // format submission JsonFormatterWithFilters formatter = new JsonFormatterWithFilters(pWriter, form, null, option, true, cc.getServerURL()); formatter.processSubmissions(Collections.singletonList(submission), cc); pWriter.flush(); JsonParser parser = new JsonParser(); JsonElement submissionJsonObj = parser.parse(baStream.toString(HtmlConsts.UTF8_ENCODE)); // create json object JsonObject entity = new JsonObject(); entity.addProperty("token", getAuthKey()); entity.addProperty("content", "record"); entity.addProperty("formId", form.getFormId()); entity.addProperty("formVersion", form.getMajorMinorVersionString()); entity.add("data", submissionJsonObj); StringEntity postentity = new StringEntity(entity.toString()); postentity.setContentType("application/json"); this.sendRequest(getServerUrl(), postentity, cc); } catch (ODKExternalServiceCredentialsException e) { fsc.setOperationalStatus(OperationalStatus.BAD_CREDENTIALS); try { persist(cc); } catch (Exception e1) { e1.printStackTrace(); throw new ODKExternalServiceException("unable to persist bad credentials status", e1); } throw e; // don't wrap } catch (ODKExternalServiceException e) { throw e; // don't wrap } catch (Exception e) { throw new ODKExternalServiceException(e); } }