List of usage examples for org.apache.http.protocol HTTP CONTENT_TYPE
String CONTENT_TYPE
To view the source code for org.apache.http.protocol HTTP CONTENT_TYPE.
Click Source Link
From source file:at.alladin.rmbt.client.helper.JSONParser.java
public JSONObject sendJSONToUrl(final URI uri, final JSONObject data) { JSONObject jObj = null;//from w w w . j a v a2 s. c o m String responseBody; try { final HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 20000); HttpConnectionParams.setSoTimeout(params, 20000); final HttpClient client = new DefaultHttpClient(params); final HttpPost httppost = new HttpPost(uri); final StringEntity se = new StringEntity(data.toString(), "UTF-8"); httppost.setEntity(se); httppost.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8")); final ResponseHandler<String> responseHandler = new BasicResponseHandler(); responseBody = client.execute(httppost, responseHandler); // try parse the string to a JSON object try { jObj = new JSONObject(responseBody); } catch (final JSONException e) { writeErrorList("Error parsing JSON " + e.toString()); } } catch (final UnsupportedEncodingException e) { writeErrorList("Wrong encoding"); // e.printStackTrace(); } catch (final HttpResponseException e) { writeErrorList( "Server responded with Code " + e.getStatusCode() + " and message '" + e.getMessage() + "'"); } catch (final ClientProtocolException e) { writeErrorList("Wrong Protocol"); // e.printStackTrace(); } catch (final ConnectTimeoutException e) { writeErrorList("ConnectionTimeoutException"); e.printStackTrace(); } catch (final IOException e) { writeErrorList("IO Exception"); e.printStackTrace(); } if (jObj == null) jObj = createErrorJSON(); // return JSONObject return jObj; }
From source file:org.piwik.sdk.TrackerBulkURLProcessor.java
public boolean doPost(URL url, JSONObject json) { if (url == null || json == null) { return false; }// w w w. j a v a 2s . c o m String jsonBody = json.toString(); try { HttpPost post = new HttpPost(url.toURI()); StringEntity se = new StringEntity(jsonBody); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(se); return doRequest(post, jsonBody); } catch (URISyntaxException e) { Log.w(Tracker.LOGGER_TAG, String.format("URI Syntax Error %s", url.toString()), e); } catch (UnsupportedEncodingException e) { Log.w(Tracker.LOGGER_TAG, String.format("Unsupported Encoding %s", jsonBody), e); } return false; }
From source file:org.alfresco.provision.BMService.java
/** * Populate HTTP message call with given content. * /* w w w . ja v a2 s . c o m*/ * @param json * {@link JSONObject} content * @return {@link StringEntity} content. * @throws UnsupportedEncodingException * if unsupported */ public StringEntity setMessageBody(final JSONObject json) throws UnsupportedEncodingException { if (json == null || json.toString().isEmpty()) throw new UnsupportedOperationException("JSON Content is required."); StringEntity se = setMessageBody(json.toString()); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, MIME_TYPE_JSON)); return se; }
From source file:org.awesomeagile.integrations.hackpad.HackpadClientTest.java
@Test(expected = RuntimeException.class) public void testUpdateHackpadFailure() { String newContent = "<html><body>This is a new content</body></html>"; String padId = RandomStringUtils.randomAlphanumeric(16); mockServer.expect(requestTo("http://test/api/1.0/pad/" + padId + "/content")) .andExpect(method(HttpMethod.POST)).andExpect(header(HTTP.CONTENT_TYPE, MediaType.TEXT_HTML_VALUE)) .andExpect(content().string(newContent)) .andRespond(withSuccess("{\"success\": false}", MediaType.APPLICATION_JSON)); client.updateHackpad(new PadIdentity(padId), newContent); }
From source file:com.google.android.gcm.demo.app.utils.ServerUtilities.java
/** * Issue a POST request to the server./*from ww w . j a v a2 s . c om*/ * * @param endpoint POST address. * @param json object to send. * @throws IOException propagated from PUT. */ private static HttpResponse doHttpPut(String endpoint, JSONObject json) throws IOException { HttpPut putRequest = new HttpPut(endpoint); putRequest.setEntity(new StringEntity(json.toString())); putRequest.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); return executeRequest(putRequest); }
From source file:com.example.android.donebar.DoneBarActivity.java
public void sendJSON(JSONObject obj) { StringEntity se = null;//from w w w . j a v a2 s .c o m try { 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.spoiledmilk.ibikecph.util.HttpUtils.java
public static JsonNode postToServer(String urlString, JSONObject objectToPost) { JsonNode ret = null;/* w w w . ja va 2 s .c o m*/ LOG.d("POST api request, url = " + urlString + " object = " + objectToPost.toString()); HttpParams myParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(myParams, CONNECTON_TIMEOUT); HttpConnectionParams.setSoTimeout(myParams, CONNECTON_TIMEOUT); HttpClient httpclient = new DefaultHttpClient(myParams); httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Config.USER_AGENT); HttpPost httppost = null; URL url = null; try { url = new URL(urlString); httppost = new HttpPost(url.toString()); httppost.setHeader("Content-type", "application/json"); httppost.setHeader("Accept", ACCEPT); httppost.setHeader("LANGUAGE_CODE", IbikeApplication.getLanguageString()); StringEntity se = new StringEntity(objectToPost.toString(), HTTP.UTF_8);// , HTTP.UTF_8 se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); httppost.setEntity(se); HttpResponse response = httpclient.execute(httppost); String serverResponse = EntityUtils.toString(response.getEntity()); LOG.d("API response = " + serverResponse); ret = Util.stringToJsonNode(serverResponse); } catch (Exception e) { if (e != null && e.getLocalizedMessage() != null) { LOG.e(e.getLocalizedMessage()); } } return ret; }
From source file:test.portlet.service.impl.MolgenisAPIRequestLocalServiceImpl.java
public void testAPIUpdate() { String url = "http://catalogue.rd-connect.eu/apiv1/update"; System.out.println("-- API Update Test: " + url); try {/* www.j ava 2 s .com*/ HttpClient c = HttpClientBuilder.create().build(); HttpPost p = new HttpPost(url); BASE64Encoder base = new BASE64Encoder(); String encoding = base.encode("jud@patientcrossroads.com:rdc2016".getBytes()); p.addHeader("Authorization", "Basic " + encoding); p.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); System.out.println("Authorization:" + encoding); String entry = "[{\"/update-portlet.idcard/diseasematrix\": {\"url\": \"https://connect.patientcrossroads.org/?org=algsa\",\"diseasname\": \"Alagille Syndrome 1\",\"patientcount\": \"\",\"gene\": \"JAG1\",\"orphanumber\": \"ORPHA52\",\"icd10\": \"Q44.7\",\"omim\": \"#610205\",\"synonym\": \"ALGS1\"}}]"; p.setEntity(new StringEntity(entry, ContentType.APPLICATION_JSON)); HttpResponse r = c.execute(p); BufferedReader rd = new BufferedReader(new InputStreamReader(r.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { // Parse our JSON response System.out.println(line); } } catch (Exception e) { System.out.println(e); } }
From source file:org.envirocar.app.dao.remote.RemoteSensorDAO.java
private String registerSensor(String sensorString) throws IOException, NotConnectedException, UnauthorizedException, ResourceConflictException { HttpPost postRequest = new HttpPost(ECApplication.BASE_URL + "/sensors"); StringEntity se = new StringEntity(sensorString); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); postRequest.setEntity(se);/*from w w w .j a v a2 s. co m*/ HttpResponse response = super.executePayloadRequest(postRequest); Header[] h = response.getAllHeaders(); String location = ""; for (int i = 0; i < h.length; i++) { if (h[i].getName().equals("Location")) { location += h[i].getValue(); break; } } logger.info("location: " + location); return location.substring(location.lastIndexOf("/") + 1, location.length()); }
From source file:com.paramedic.mobshaman.activities.AccessTimeActivity.java
public void postAccessTime() { Gson g = new Gson(); String jsonAccessTime = g.toJson(getMobileAccessTime()); StringEntity entity = null;/*from w ww . ja v a 2s .c o m*/ try { entity = new StringEntity(jsonAccessTime); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); // URL_HC = "http://10.0.3.2/wapimobile/api/mobileaccesstime?licencia=5688923116"; ServiciosRestClient.post(context, URL_HC, entity, "application/json", new JsonHttpResponseHandler() { @Override public void onStart() { String message = TipoMovimiento == 0 ? "Registrando ingreso..." : "Registrando egreso..."; pDialog.setMessage(message); pDialog.show(); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); Utils.showToast(getApplicationContext(), "Error " + statusCode + ": " + throwable.getMessage()); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); Utils.showToast(getApplicationContext(), "Error " + statusCode + ": " + throwable.getMessage()); } @Override public void onSuccess(int statusCode, Header[] headers, JSONObject result) { Utils.showToast(getApplicationContext(), result.toString()); startActivity(intent); } @Override public void onFinish() { pDialog.dismiss(); } }); }