List of usage examples for org.json JSONObject toString
public String toString()
From source file:de.jaetzold.philips.hue.HueBridgeComm.java
@SuppressWarnings("UnusedDeclaration") List<JSONObject> request(RM method, String fullPath, JSONObject json) throws IOException { return request(method, fullPath, json.toString()); }
From source file:com.intel.iotkitlib.LibModules.AdvancedDataEnquiry.java
private String createBodyForAdvancedDataInquiry() throws JSONException { JSONObject dataInquiryJson = new JSONObject(); if (this.msgType == null) { dataInquiryJson.put("msgType", "advancedDataInquiryRequest"); } else {/*from www .j a v a2 s . c om*/ dataInquiryJson.put("msgType", this.msgType); } if (this.gatewayIds != null) { JSONArray gatewayArray = new JSONArray(); for (String gatewayId : this.gatewayIds) { gatewayArray.put(gatewayId); } dataInquiryJson.put("gatewayIds", gatewayArray); } if (this.deviceIds != null) { JSONArray deviceIdArray = new JSONArray(); for (String deviceId : this.deviceIds) { deviceIdArray.put(deviceId); } dataInquiryJson.put("deviceIds", deviceIdArray); } if (this.componentIds != null) { JSONArray componentIdArray = new JSONArray(); for (String componentId : this.componentIds) { componentIdArray.put(componentId); } dataInquiryJson.put("componentIds", componentIdArray); } dataInquiryJson.put("startTimestamp", this.startTimestamp); dataInquiryJson.put("endTimestamp", this.endTimestamp); /*dataInquiryJson.put("from", this.startTimestamp); dataInquiryJson.put("to", this.endTimestamp);*/ //returnedMeasureAttributes if (this.returnedMeasureAttributes != null) { JSONArray returnedMeasureAttributesArray = new JSONArray(); for (String attribute : this.returnedMeasureAttributes) { returnedMeasureAttributesArray.put(attribute); } dataInquiryJson.put("returnedMeasureAttributes", returnedMeasureAttributesArray); } if (this.showMeasureLocation) { dataInquiryJson.put("showMeasureLocation", this.showMeasureLocation); } if (this.componentRowLimit > 0) { dataInquiryJson.put("componentRowLimit", this.componentRowLimit); } //sort if (this.sort != null) { JSONArray sortArray = new JSONArray(); for (NameValuePair nameValuePair : this.sort) { JSONObject nameValueJson = new JSONObject(); nameValueJson.put(nameValuePair.getName(), nameValuePair.getValue()); sortArray.put(nameValueJson); } dataInquiryJson.put("sort", sortArray); } if (this.countOnly) { dataInquiryJson.put("countOnly", this.countOnly); } if (this.devCompAttributeFilter != null) { JSONObject devCompAttributeJson = new JSONObject(); for (AttributeFilter attributeFilter : this.devCompAttributeFilter.filterData) { JSONArray filterValuesArray = new JSONArray(); for (String filterValue : attributeFilter.filterValues) { filterValuesArray.put(filterValue); } devCompAttributeJson.put(attributeFilter.filterName, filterValuesArray); } dataInquiryJson.put("devCompAttributeFilter", devCompAttributeJson); } if (this.measurementAttributeFilter != null) { JSONObject measurementAttributeJson = new JSONObject(); for (AttributeFilter attributeFilter : this.measurementAttributeFilter.filterData) { JSONArray filterValuesArray = new JSONArray(); for (String filterValue : attributeFilter.filterValues) { filterValuesArray.put(filterValue); } measurementAttributeJson.put(attributeFilter.filterName, filterValuesArray); } dataInquiryJson.put("measurementAttributeFilter", measurementAttributeJson); } if (this.valueFilter != null) { JSONObject valueFilterJson = new JSONObject(); JSONArray filterValuesArray = new JSONArray(); for (String filterValue : this.valueFilter.filterValues) { filterValuesArray.put(filterValue); } valueFilterJson.put(this.valueFilter.filterName, filterValuesArray); dataInquiryJson.put("valueFilter", valueFilterJson); } return dataInquiryJson.toString(); }
From source file:com.percolatestudio.cordova.fileupload.PSFileUpload.java
/** * Uploads the specified file to the server URL provided using an HTTP multipart request. * @param source Full path of the file on the file system * @param target URL of the server to receive the file * @param args JSON Array of args * @param callbackContext callback id for optional progress reports * * args[2] fileKey Name of file request parameter * args[3] fileName File name to be used on server * args[4] mimeType Describes file content type * args[5] params key:value pairs of user-defined parameters * @return FileUploadResult containing result of upload request *///from w ww .java 2 s .c o m private void upload(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException { Log.d(LOG_TAG, "upload " + source + " to " + target); // Setup the options final String mimeType = getArgument(args, 4, "image/jpeg"); final JSONObject params = args.optJSONObject(5) == null ? new JSONObject() : args.optJSONObject(5); final boolean trustEveryone = args.optBoolean(6); // Always use chunked mode unless set to false as per API final boolean chunkedMode = args.optBoolean(7) || args.isNull(7); // Look for headers on the params map for backwards compatibility with older Cordova versions. final JSONObject headers = args.optJSONObject(8) == null ? params.optJSONObject("headers") : args.optJSONObject(8); final String objectId = args.getString(9); final String httpMethod = getArgument(args, 10, "POST"); final CordovaResourceApi resourceApi = webView.getResourceApi(); Log.d(LOG_TAG, "mimeType: " + mimeType); Log.d(LOG_TAG, "params: " + params); Log.d(LOG_TAG, "trustEveryone: " + trustEveryone); Log.d(LOG_TAG, "chunkedMode: " + chunkedMode); Log.d(LOG_TAG, "headers: " + headers); Log.d(LOG_TAG, "objectId: " + objectId); Log.d(LOG_TAG, "httpMethod: " + httpMethod); final Uri targetUri = resourceApi.remapUri(Uri.parse(target)); // Accept a path or a URI for the source. Uri tmpSrc = Uri.parse(source); final Uri sourceUri = resourceApi .remapUri(tmpSrc.getScheme() != null ? tmpSrc : Uri.fromFile(new File(source))); int uriType = CordovaResourceApi.getUriType(targetUri); final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS; if (uriType != CordovaResourceApi.URI_TYPE_HTTP && !useHttps) { JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0); Log.e(LOG_TAG, "Unsupported URI: " + targetUri); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); return; } final RequestContext context = new RequestContext(source, target, callbackContext); synchronized (activeRequests) { activeRequests.put(objectId, context); } cordova.getThreadPool().execute(new Runnable() { public void run() { if (context.aborted) { return; } HttpURLConnection conn = null; HostnameVerifier oldHostnameVerifier = null; SSLSocketFactory oldSocketFactory = null; int totalBytes = 0; int fixedLength = -1; try { // Create return object PSFileUploadResult result = new PSFileUploadResult(); PSFileProgressResult progress = new PSFileProgressResult(); //------------------ CLIENT REQUEST // Open a HTTP connection to the URL based on protocol conn = resourceApi.createHttpConnection(targetUri); if (useHttps && trustEveryone) { // Setup the HTTPS connection class to trust everyone HttpsURLConnection https = (HttpsURLConnection) conn; oldSocketFactory = trustAllHosts(https); // Save the current hostnameVerifier oldHostnameVerifier = https.getHostnameVerifier(); // Setup the connection not to verify hostnames https.setHostnameVerifier(DO_NOT_VERIFY); } // Allow Inputs conn.setDoInput(true); // Allow Outputs conn.setDoOutput(true); // Don't use a cached copy. conn.setUseCaches(false); // Use a post method. conn.setRequestMethod(httpMethod); conn.setRequestProperty("Content-Type", mimeType); // Set the cookies on the response String cookie = CookieManager.getInstance().getCookie(target); if (cookie != null) { conn.setRequestProperty("Cookie", cookie); } // Handle the other headers if (headers != null) { addHeadersToRequest(conn, headers); } // Get a input stream of the file on the phone OpenForReadResult readResult = resourceApi.openForRead(sourceUri); if (readResult.length >= 0) { fixedLength = (int) readResult.length; progress.setLengthComputable(true); progress.setTotal(fixedLength); } Log.d(LOG_TAG, "Content Length: " + fixedLength); // setFixedLengthStreamingMode causes and OutOfMemoryException on pre-Froyo devices. // http://code.google.com/p/android/issues/detail?id=3164 // It also causes OOM if HTTPS is used, even on newer devices. boolean useChunkedMode = chunkedMode && (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO || useHttps); useChunkedMode = useChunkedMode || (fixedLength == -1); if (useChunkedMode) { conn.setChunkedStreamingMode(MAX_BUFFER_SIZE); // Although setChunkedStreamingMode sets this header, setting it explicitly here works // around an OutOfMemoryException when using https. conn.setRequestProperty("Transfer-Encoding", "chunked"); } else { conn.setFixedLengthStreamingMode(fixedLength); } conn.connect(); OutputStream sendStream = null; try { sendStream = conn.getOutputStream(); synchronized (context) { if (context.aborted) { return; } context.currentOutputStream = sendStream; } //We don't want to change encoding, we just want this to write for all Unicode. // create a buffer of maximum size int bytesAvailable = readResult.inputStream.available(); int bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE); byte[] buffer = new byte[bufferSize]; // read file and write it into form... int bytesRead = readResult.inputStream.read(buffer, 0, bufferSize); long prevBytesRead = 0; while (bytesRead > 0) { result.setBytesSent(totalBytes); sendStream.write(buffer, 0, bytesRead); totalBytes += bytesRead; if (totalBytes > prevBytesRead + 102400) { prevBytesRead = totalBytes; Log.d(LOG_TAG, "Uploaded " + totalBytes + " of " + fixedLength + " bytes"); } bytesAvailable = readResult.inputStream.available(); bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE); bytesRead = readResult.inputStream.read(buffer, 0, bufferSize); // Send a progress event. progress.setLoaded(totalBytes); PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject()); progressResult.setKeepCallback(true); context.sendPluginResult(progressResult); } sendStream.flush(); } finally { safeClose(readResult.inputStream); safeClose(sendStream); } context.currentOutputStream = null; Log.d(LOG_TAG, "Sent " + totalBytes + " of " + fixedLength); //------------------ read the SERVER RESPONSE String responseString; int responseCode = conn.getResponseCode(); Log.d(LOG_TAG, "response code: " + responseCode); Log.d(LOG_TAG, "response headers: " + conn.getHeaderFields()); TrackingInputStream inStream = null; try { inStream = getInputStream(conn); synchronized (context) { if (context.aborted) { return; } context.currentInputStream = inStream; } ByteArrayOutputStream out = new ByteArrayOutputStream( Math.max(1024, conn.getContentLength())); byte[] buffer = new byte[1024]; int bytesRead = 0; // write bytes to file while ((bytesRead = inStream.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); } responseString = out.toString("UTF-8"); } finally { context.currentInputStream = null; safeClose(inStream); } Log.d(LOG_TAG, "got response from server"); Log.d(LOG_TAG, responseString.substring(0, Math.min(256, responseString.length()))); // send request and retrieve response result.setResponseCode(responseCode); result.setResponse(responseString); context.sendPluginResult(new PluginResult(PluginResult.Status.OK, result.toJSONObject())); } catch (FileNotFoundException e) { JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn); Log.e(LOG_TAG, error.toString(), e); context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); } catch (IOException e) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn); Log.e(LOG_TAG, error.toString(), e); Log.e(LOG_TAG, "Failed after uploading " + totalBytes + " of " + fixedLength + " bytes."); context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); context.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } catch (Throwable t) { // Shouldn't happen, but will JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn); Log.e(LOG_TAG, error.toString(), t); context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); } finally { synchronized (activeRequests) { activeRequests.remove(objectId); } if (conn != null) { // Revert back to the proper verifier and socket factories // Revert back to the proper verifier and socket factories if (trustEveryone && useHttps) { HttpsURLConnection https = (HttpsURLConnection) conn; https.setHostnameVerifier(oldHostnameVerifier); https.setSSLSocketFactory(oldSocketFactory); } } } } }); }
From source file:com.facebook.stetho.inspector.jsonrpc.JsonRpcPeer.java
public void invokeMethod(String method, Object paramsObject, @Nullable PendingRequestCallback callback) throws NotYetConnectedException { Util.throwIfNull(method);/*from w w w. ja v a2 s .c o m*/ Long requestId = (callback != null) ? preparePendingRequest(callback) : null; // magic, can basically convert anything for some amount of runtime overhead... JSONObject params = mObjectMapper.convertValue(paramsObject, JSONObject.class); JsonRpcRequest message = new JsonRpcRequest(requestId, method, params); String requestString; JSONObject jsonObject = mObjectMapper.convertValue(message, JSONObject.class); requestString = jsonObject.toString(); mPeer.sendText(requestString); }
From source file:com.pinch.console.GcmSender.java
public static void main(String[] args) { // if (args.length < 1 || args.length > 2 || args[0] == null) { // System.err.println("usage: ./gradlew run -Pmsg=\"MESSAGE\" [-Pto=\"DEVICE_TOKEN\"]"); // System.err.println(""); // System.err.println("Specify a test message to broadcast via GCM. If a device's GCM registration token is\n" + // "specified, the message will only be sent to that device. Otherwise, the message \n" + // "will be sent to all devices subscribed to the \"global\" topic."); // System.err.println(""); // System.err.println("Example (Broadcast):\n" + // "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\"\n" + // "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\""); // System.err.println(""); // System.err.println("Example (Unicast):\n" + // "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\"\n" + // "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\""); // System.exit(1); // }/*from www . ja va2 s .c o m*/ try { // Prepare JSON containing the GCM message content. What to send and where to send. JSONObject jGcmData = new JSONObject(); JSONObject jData = new JSONObject(); jData.put("message", "Saurabh Garg signed up!!"); jData.put("title", "New sign up!"); // Where to send GCM message. //if (args.length > 1 && args[1] != null) { jGcmData.put("to", "dOEmVpNPTCY:APA91bEkeYfFMhAraF4d87SJu12oxDElUp6KW1r710KSKeuDpW31Cd5_WExUxT16KNquJ69wwDMlxd-3qoEIeDNJNU1XjyXiXztOqlKglB-zdOlszoXhX9zIYmYNV8d4vWkM0oPwjlk9"); // } else { // jGcmData.put("to", "/topics/global"); // } // What to send in GCM message. jGcmData.put("data", jData); // Create connection to send GCM Message request. URL url = new URL("https://android.googleapis.com/gcm/send"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "key=" + API_KEY); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestMethod("POST"); conn.setDoOutput(true); // Send GCM message content. OutputStream outputStream = conn.getOutputStream(); outputStream.write(jGcmData.toString().getBytes()); // Read GCM response. InputStream inputStream = conn.getInputStream(); String resp = IOUtils.toString(inputStream); System.out.println(resp); System.out.println("Check your device/emulator for notification or logcat for " + "confirmation of the receipt of the GCM message."); } catch (IOException e) { System.out.println("Unable to send GCM message."); System.out.println("Please ensure that API_KEY has been replaced by the server " + "API key, and that the device's registration token is correct (if specified)."); e.printStackTrace(); } }
From source file:org.akvo.caddisfly.sensor.colorimetry.strip.ui.ResultActivity.java
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_result); setTitle(R.string.result);//from ww w .ja v a 2 s . c om buttonSave = (Button) findViewById(R.id.button_save); buttonSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getIntent()); String path; if (getIntent().getBooleanExtra(Constant.SEND_IMAGE_IN_RESULT, false) && resultImage != null) { // store image on sd card path = FileUtil.writeBitmapToExternalStorage(ResultUtil.makeBitmap(resultImage), "/result-images", resultImageUrl); intent.putExtra(SensorConstants.IMAGE, path); if (path.length() == 0) { resultImageUrl = ""; } } else { resultImageUrl = ""; } TestInfo testInfo = CaddisflyApp.getApp().getCurrentTestInfo(); StripTest stripTest = new StripTest(); // get information on the strip test from JSON StripTest.Brand brand = stripTest.getBrand(testInfo.getId()); JSONObject resultJsonObj = TestConfigHelper.getJsonResult(testInfo, results, -1, resultImageUrl, brand.getGroupingType()); intent.putExtra(SensorConstants.RESPONSE, resultJsonObj.toString()); setResult(RESULT_OK, intent); finish(); } }); buttonCancel = (Button) findViewById(R.id.button_cancel); buttonCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getIntent()); setResult(RESULT_CANCELED, intent); finish(); } }); if (savedInstanceState == null) { int format = getIntent().getIntExtra(Constant.FORMAT, 0); int width = getIntent().getIntExtra(Constant.WIDTH, 0); int height = getIntent().getIntExtra(Constant.HEIGHT, 0); Intent detectStripIntent = createDetectStripIntent(format, width, height); new DetectStripTask(this).execute(detectStripIntent); } }
From source file:org.openmrs.mobile.listeners.visit.StartVisitListener.java
@Override public void onResponse(JSONObject response) { mLogger.d(response.toString()); try {/* w w w. j a va 2s . c om*/ long visitID = new VisitDAO().saveVisit(VisitMapper.map(response), mPatientID); callerAction(visitID); } catch (JSONException e) { mLogger.d(e.toString()); } }
From source file:com.norman0406.slimgress.API.Interface.Interface.java
public void handshake(final Handshake.Callback callback) { new Thread(new Runnable() { @Override//from w w w .jav a2 s .c om public void run() { JSONObject params = new JSONObject(); try { // set handshake parameters params.put("nemesisSoftwareVersion", mApiVersion); params.put("deviceSoftwareVersion", Build.VERSION.RELEASE); // TODO: /*params.put("activationCode", ""); params.put("tosAccepted", "1"); params.put("a", "");*/ String paramString = params.toString(); paramString = URLEncoder.encode(paramString, "UTF-8"); String handshake = mApiBaseURL + mApiHandshake + paramString; HttpGet get = new HttpGet(handshake); get.setHeader("Accept-Charset", "utf-8"); get.setHeader("Cache-Control", "max-age=0"); // do handshake HttpResponse response = null; synchronized (Interface.this) { Log.i("Interface", "executing handshake"); response = mClient.execute(get); } assert (response != null); HttpEntity entity = response.getEntity(); if (entity != null) { String content = EntityUtils.toString(entity); Header contentType = entity.getContentType(); entity.consumeContent(); // check for content type json if (!contentType.getName().equals("Content-Type") || !contentType.getValue().contains("application/json")) throw new RuntimeException("content type is not json"); content = content.replace("while(1);", ""); // handle handshake data callback.handle(new Handshake(new JSONObject(content))); Log.i("Interface", "handshake finished"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } }).start(); }
From source file:com.norman0406.slimgress.API.Interface.Interface.java
public void request(final Handshake handshake, final String requestString, final Location playerLocation, final JSONObject requestParams, final RequestResult result) throws InterruptedException { if (!handshake.isValid() || handshake.getXSRFToken().length() == 0) throw new RuntimeException("handshake is not valid"); new Thread(new Runnable() { public void run() { // create post String postString = mApiBaseURL + mApiRequest + requestString; HttpPost post = new HttpPost(postString); // set additional parameters JSONObject params = new JSONObject(); if (requestParams != null) { if (requestParams.has("params")) params = requestParams; else { try { params.put("params", requestParams); // add persistent request parameters if (playerLocation != null) { String loc = String.format("%08x,%08x", playerLocation.getLatitude(), playerLocation.getLongitude()); params.getJSONObject("params").put("playerLocation", loc); params.getJSONObject("params").put("location", loc); }/*from w w w.j a va 2s . c om*/ params.getJSONObject("params").put("knobSyncTimestamp", getCurrentTimestamp()); JSONArray collectedEnergy = new JSONArray(); // TODO: add collected energy guids params.getJSONObject("params").put("energyGlobGuids", collectedEnergy); } catch (JSONException e) { e.printStackTrace(); } } } else { try { params.put("params", null); } catch (JSONException e) { e.printStackTrace(); } } try { StringEntity entity = new StringEntity(params.toString(), "UTF-8"); entity.setContentType("application/json"); post.setEntity(entity); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // set header post.setHeader("Content-Type", "application/json;charset=UTF-8"); post.setHeader("Accept-Encoding", "gzip"); post.setHeader("User-Agent", "Nemesis (gzip)"); post.setHeader("X-XsrfToken", handshake.getXSRFToken()); post.setHeader("Host", mApiBase); post.setHeader("Connection", "Keep-Alive"); post.setHeader("Cookie", "SACSID=" + mCookie); // execute and get the response. try { HttpResponse response = null; String content = null; synchronized (Interface.this) { response = mClient.execute(post); assert (response != null); if (response.getStatusLine().getStatusCode() == 401) { // token expired or similar //isAuthenticated = false; response.getEntity().consumeContent(); } else { HttpEntity entity = response.getEntity(); // decompress gzip if necessary Header contentEncoding = entity.getContentEncoding(); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) content = decompressGZIP(entity); else content = EntityUtils.toString(entity); entity.consumeContent(); } } // handle request result if (content != null) { JSONObject json = new JSONObject(content); RequestResult.handleRequest(json, result); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } }).start(); }
From source file:eu.codeplumbers.cosi.services.CosiExpenseService.java
public void sendChangesToCozy() { List<Expense> unSyncedExpenses = Expense.getAllUnsynced(); int i = 0;/*from w w w . ja v a2 s . c o m*/ for (Expense expense : unSyncedExpenses) { URL urlO = null; try { JSONObject jsonObject = expense.toJsonObject(); mBuilder.setProgress(unSyncedExpenses.size(), i + 1, false); mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":"); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault().post( new ExpenseSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_expense_status_read_phone))); String remoteId = jsonObject.getString("remoteId"); String requestMethod = ""; if (remoteId.isEmpty()) { urlO = new URL(syncUrl); requestMethod = "POST"; } else { urlO = new URL(syncUrl + remoteId + "/"); requestMethod = "PUT"; } HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod(requestMethod); // set request body jsonObject.remove("remoteId"); long objectId = jsonObject.getLong("id"); jsonObject.remove("id"); OutputStream os = conn.getOutputStream(); os.write(jsonObject.toString().getBytes("UTF-8")); os.flush(); // read the response InputStream in = new BufferedInputStream(conn.getInputStream()); StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); JSONObject jsonObjectResult = new JSONObject(result); if (jsonObjectResult != null && jsonObjectResult.has("_id")) { result = jsonObjectResult.getString("_id"); expense.setRemoteId(result); expense.save(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } catch (JSONException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } i++; } }