List of usage examples for org.json JSONObject getString
public String getString(String key) throws JSONException
From source file:com.escapeir.server.Connect.java
@Override protected Boolean doInBackground(Boolean... params) { HttpPost httppost = null;//w w w .j a v a 2 s . c o m // setOrGet = true is set user // setOrGet = false is Get user setOrGet = params[0]; String urlExecute = "", urlSet = "http://escapeir.uphero.com/setUser.php", urlGet = "http://escapeir.uphero.com/getUser.php"; String result = ""; InputStream is = null; try { HttpClient httpclient = new DefaultHttpClient(); if (setOrGet) { httppost = new HttpPost(urlSet); final ArrayList<NameValuePair> insertUser = new ArrayList<NameValuePair>(); insertUser.add(new BasicNameValuePair("user", EscapeIRApplication.USER_NAME)); insertUser.add(new BasicNameValuePair("time", EscapeIRApplication.USER_TIME)); httppost.setEntity(new UrlEncodedFormEntity(insertUser)); } else { httppost = new HttpPost(urlGet); } HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); Log.i("Connect", "Connect"); } catch (Exception e) { Log.e(EscapeIRApplication.TAG, "Error in http connection " + e.toString()); } // convert response to string try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); Log.i(EscapeIRApplication.TAG, "resultado"); Log.i(EscapeIRApplication.TAG, result); } catch (Exception e) { Log.e(EscapeIRApplication.TAG, "Error converting result " + e.toString()); } // parse json data if (setOrGet) { // return if is set user return true; } else { try { JSONArray jArray = new JSONArray(result); for (int i = 0; i < jArray.length(); i++) { JSONObject json_data = jArray.getJSONObject(i); EscapeIRApplication.usersServer .add(new User(json_data.getString("user"), json_data.getString("time"))); Log.i(EscapeIRApplication.TAG, "time: " + json_data.getString("time") + ", name: " + json_data.getString("user")); } } catch (JSONException e) { Log.e(EscapeIRApplication.TAG, "Error parsing data " + e.toString()); } } return true; }
From source file:org.zywx.wbpalmstar.platform.push.report.PushReportAgent.java
/** * ???msgId//ww w . j a v a2 s .c om * * @param pushInfo * @return */ private static String parsePushInfo2MsgId(String pushInfo) { String msgId = null; try { JSONObject json = new JSONObject(pushInfo); msgId = json.getString(KEY_PUSH_REPORT_MSGID); } catch (Exception e) { PushReportUtility.oe("parsePushInfo2MsgId", e); } return msgId; }
From source file:org.wso2.app.catalog.LoginActivity.java
/** * Start authentication process.//from www. ja v a2s .co m */ private void startAuthentication() { // Check network connection availability before calling the API. if (CommonUtils.isNetworkAvailable(context)) { String clientId = Preference.getString(context, Constants.CLIENT_ID); String clientSecret = Preference.getString(context, Constants.CLIENT_SECRET); String clientName; if (clientId == null || clientSecret == null) { String clientCredentials = Preference.getString(context, getResources().getString(R.string.shared_pref_client_credentials)); if (clientCredentials != null) { try { JSONObject payload = new JSONObject(clientCredentials); clientId = payload.getString(Constants.CLIENT_ID); clientSecret = payload.getString(Constants.CLIENT_SECRET); clientName = payload.getString(Constants.CLIENT_NAME); if (clientName != null && !clientName.isEmpty()) { Preference.putString(context, Constants.CLIENT_NAME, clientName); } if (clientId != null && !clientId.isEmpty() && clientSecret != null && !clientSecret.isEmpty()) { initializeIDPLib(clientId, clientSecret); } } catch (JSONException e) { String msg = "error occurred while parsing client credential payload"; Log.e(TAG, msg, e); CommonDialogUtils.stopProgressDialog(progressDialog); showInternalServerErrorMessage(); } } else { String msg = "error occurred while retrieving client credentials"; Log.e(TAG, msg); CommonDialogUtils.stopProgressDialog(progressDialog); showInternalServerErrorMessage(); } } else { initializeIDPLib(clientId, clientSecret); } } else { CommonDialogUtils.stopProgressDialog(progressDialog); CommonDialogUtils.showNetworkUnavailableMessage(context); } }
From source file:com.neuron.trafikanten.dataProviders.trafikanten.TrafikantenRealtime.java
@Override public void run() { try {// w w w . j a v a 2 s . c om final String urlString = Trafikanten.getApiUrl() + "/reisrest/realtime/GetAllDepartures/" + stationId; Log.i(TAG, "Loading realtime data : " + urlString); final StreamWithTime streamWithTime = HelperFunctions.executeHttpRequest(context, new HttpGet(urlString), true); ThreadHandleTimeData(streamWithTime.timeDifference); /* * Parse json */ //long perfSTART = System.currentTimeMillis(); //Log.i(TAG,"PERF : Getting realtime data"); final JSONArray jsonArray = new JSONArray(HelperFunctions.InputStreamToString(streamWithTime.stream)); final int arraySize = jsonArray.length(); for (int i = 0; i < arraySize; i++) { final JSONObject json = jsonArray.getJSONObject(i); RealtimeData realtimeData = new RealtimeData(); try { realtimeData.expectedDeparture = HelperFunctions .jsonToDate(json.getString("ExpectedDepartureTime")); } catch (org.json.JSONException e) { realtimeData.expectedDeparture = HelperFunctions .jsonToDate(json.getString("ExpectedArrivalTime")); } try { realtimeData.lineId = json.getInt("LineRef"); } catch (org.json.JSONException e) { realtimeData.lineId = -1; } try { realtimeData.vehicleMode = json.getInt("VehicleMode"); } catch (org.json.JSONException e) { realtimeData.vehicleMode = 0; // default = bus } try { realtimeData.destination = json.getString("DestinationName"); } catch (org.json.JSONException e) { realtimeData.destination = "Ukjent"; } try { realtimeData.departurePlatform = json.getString("DeparturePlatformName"); if (realtimeData.departurePlatform.equals("null")) { realtimeData.departurePlatform = ""; } } catch (org.json.JSONException e) { realtimeData.departurePlatform = ""; } try { realtimeData.realtime = json.getBoolean("Monitored"); } catch (org.json.JSONException e) { realtimeData.realtime = false; } try { realtimeData.lineName = json.getString("PublishedLineName"); } catch (org.json.JSONException e) { realtimeData.lineName = ""; } try { if (json.has("InCongestion")) { realtimeData.inCongestion = json.getBoolean("InCongestion"); } } catch (org.json.JSONException e) { // can happen when incongestion is empty string. } try { if (json.has("VehicleFeatureRef")) { realtimeData.lowFloor = json.getString("VehicleFeatureRef").equals("lowFloor"); } } catch (org.json.JSONException e) { // lowfloor = false by default } try { if (json.has("TrainBlockPart") && !json.isNull("TrainBlockPart")) { JSONObject trainBlockPart = json.getJSONObject("TrainBlockPart"); if (trainBlockPart.has("NumberOfBlockParts")) { realtimeData.numberOfBlockParts = trainBlockPart.getInt("NumberOfBlockParts"); } } } catch (org.json.JSONException e) { // trainblockpart is initialized by default } ThreadHandlePostData(realtimeData); } //Log.i(TAG,"PERF : Parsing web request took " + ((System.currentTimeMillis() - perfSTART)) + "ms"); } catch (Exception e) { if (e.getClass() == InterruptedException.class) { ThreadHandlePostExecute(null); return; } ThreadHandlePostExecute(e); return; } ThreadHandlePostExecute(null); }
From source file:com.userhook.model.UHMessageMetaImage.java
public static UHMessageMetaImage fromJSON(JSONObject json) { UHMessageMetaImage image = new UHMessageMetaImage(); try {//ww w . ja v a2 s .co m if (json.has("url")) { image.url = json.getString("url"); } if (json.has("height")) { image.height = json.getInt("height"); } if (json.has("width")) { image.width = json.getInt("width"); } } catch (Exception e) { Log.e(UserHook.TAG, "error parsing message meta image json", e); } return image; }
From source file:com.skalski.raspberrycontrol.Custom_WebSocketClient.java
@Override public void onTextMessage(String payload) { Message payload_msg = new Message(); boolean send_message = false; try {/* w w w . jav a2 s . c om*/ JSONObject jsonObj = new JSONObject(payload); if (jsonObj.has(TAG_HAN_GPIOSTATE)) if ((this.ClientHandler != null) && (this.ClientFilter.equals(TAG_HAN_GPIOSTATE))) send_message = true; if (jsonObj.has(TAG_HAN_TEMPSENSORS)) if ((this.ClientHandler != null) && (this.ClientFilter.equals(TAG_HAN_TEMPSENSORS))) send_message = true; if (jsonObj.has(TAG_HAN_PROCESSES)) if ((this.ClientHandler != null) && (this.ClientFilter.equals(TAG_HAN_PROCESSES))) send_message = true; if (jsonObj.has(TAG_HAN_STATISTICS)) if ((this.ClientHandler != null) && (this.ClientFilter.equals(TAG_HAN_STATISTICS))) send_message = true; if (jsonObj.has(TAG_ERROR)) if (this.ClientHandler != null) send_message = true; if (jsonObj.has(TAG_HAN_NOTIFICATION)) { if (Activity_Settings.pref_notifications_disabled(getBaseContext())) { Log.i(LOGTAG, LOGPREFIX + "notification: disabled"); } else { int notification_id; if (Activity_Settings.pref_multiple_notifications_disabled(getBaseContext())) notification_id = 0; else notification_id = (int) System.currentTimeMillis(); Notification new_notification = new Notification.Builder(this) .setContentTitle(getResources().getString(R.string.app_name)) .setContentText(jsonObj.getString(TAG_HAN_NOTIFICATION)) .setSmallIcon(R.drawable.ic_launcher).build(); new_notification.defaults |= Notification.DEFAULT_ALL; NotificationManager notificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE); notificationManager.notify(notification_id, new_notification); Log.i(LOGTAG, LOGPREFIX + "notification: " + notification_id); } } } catch (JSONException e) { Log.e(LOGTAG, LOGPREFIX + "can't parse JSON object"); } if (send_message) { payload_msg.obj = payload; ClientHandler.sendMessage(payload_msg); } }
From source file:com.df.app.carsWaiting.CarsWaitingListActivity.java
/** * /*from w ww . j a v a 2 s . c om*/ * @param result */ private void fillInData(String result) { try { JSONArray jsonArray = new JSONArray(result); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); CarsWaitingItem item = new CarsWaitingItem(); item.setPlateNumber(jsonObject.getString("plateNumber")); item.setExteriorColor(jsonObject.getString("exteriorColor")); item.setCarType(jsonObject.getString("licenseModel")); item.setDate(jsonObject.getString("createDate")); item.setCarId(jsonObject.getInt("carId")); item.setJsonObject(jsonObject); data.add(item); } } catch (JSONException e) { e.printStackTrace(); } adapter.notifyDataSetChanged(); startNumber = data.size() + 1; if (data.size() == 0) { footerView.setVisibility(View.GONE); } else { footerView.setVisibility(View.VISIBLE); } // for(int i = 0; i < data.size(); i++) // swipeListView.closeAnimate(i); // // 0, ??(? // if(data.size() == 0) { // DeleteFiles.deleteFiles(AppCommon.photoDirectory); // DeleteFiles.deleteFiles(AppCommon.savedDirectory); // } }
From source file:com.klinker.android.twitter.utils.api_helper.TwitLongerHelper.java
/** * Posts the status to twitlonger/*from w ww . j a va 2 s . c om*/ * @return returns an object containing the shortened text and the id for the twitlonger url */ public TwitLongerStatus postToTwitLonger() { try { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(POST_URL); post.addHeader("X-API-KEY", TWITLONGER_API_KEY); post.addHeader("X-Auth-Service-Provider", SERVICE_PROVIDER); post.addHeader("X-Verify-Credentials-Authorization", getAuthrityHeader(twitter)); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("content", tweetText)); if (replyToId != 0) { nvps.add(new BasicNameValuePair("reply_to_id", String.valueOf(replyToId))); } else if (replyToScreenname != null) { nvps.add(new BasicNameValuePair("reply_to_screen_name", replyToScreenname)); } post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line; String content = ""; String id = ""; StringBuilder builder = new StringBuilder(); while ((line = rd.readLine()) != null) { builder.append(line); } try { // there is only going to be one thing returned ever JSONObject jsonObject = new JSONObject(builder.toString()); content = jsonObject.getString("tweet_content"); id = jsonObject.getString("id"); } catch (Exception e) { e.printStackTrace(); } Log.v("talon_twitlonger", "content: " + content); Log.v("talon_twitlonger", "id: " + id); return new TwitLongerStatus(content, id); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:eu.codeplumbers.cosi.services.CosiExpenseService.java
/** * Make remote request to get all loyalty cards stored in Cozy */// www. jav a2 s.c om public String getRemoteExpenses() { URL urlO = null; try { urlO = new URL(designUrl); HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoInput(true); conn.setRequestMethod("POST"); // read the response int status = conn.getResponseCode(); InputStream in = null; if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { in = conn.getErrorStream(); } else { in = conn.getInputStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); JSONArray jsonArray = new JSONArray(result); if (jsonArray != null) { if (jsonArray.length() == 0) { EventBus.getDefault() .post(new ExpenseSyncEvent(SYNC_MESSAGE, "Your Cozy has no expenses stored.")); Expense.setAllUnsynced(); } else { for (int i = 0; i < jsonArray.length(); i++) { try { EventBus.getDefault().post(new ExpenseSyncEvent(SYNC_MESSAGE, "Reading expenses on Cozy " + i + "/" + jsonArray.length() + "...")); JSONObject expenseJson = jsonArray.getJSONObject(i).getJSONObject("value"); Expense expense = Expense.getByRemoteId(expenseJson.get("_id").toString()); if (expense == null) { expense = new Expense(expenseJson); } else { expense.setRemoteId(expenseJson.getString("_id")); expense.setAmount(expenseJson.getDouble("amount")); expense.setCategory(expenseJson.getString("category")); expense.setDate(expenseJson.getString("date")); if (expenseJson.has("deviceId")) { expense.setDeviceId(expenseJson.getString("deviceId")); } else { expense.setDeviceId(Device.registeredDevice().getLogin()); } } expense.save(); if (expenseJson.has("receipts")) { JSONArray receiptsArray = expenseJson.getJSONArray("receipts"); for (int j = 0; j < receiptsArray.length(); j++) { JSONObject recJsonObject = receiptsArray.getJSONObject(i); Receipt receipt = new Receipt(); receipt.setBase64(recJsonObject.getString("base64")); receipt.setExpense(expense); receipt.setName(""); receipt.save(); } } } catch (JSONException e) { EventBus.getDefault() .post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } } } } else { errorMessage = new JSONObject(result).getString("error"); EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, errorMessage)); stopSelf(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (JSONException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } return errorMessage; }
From source file:eu.codeplumbers.cosi.services.CosiExpenseService.java
public void sendChangesToCozy() { List<Expense> unSyncedExpenses = Expense.getAllUnsynced(); int i = 0;//from ww w . j av a 2 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++; } }