private static JSONObject jsonError(String message) { JSONObject json = new JSONObject(); try { json.put("message", message); } catch (JSONException e) { Log.e(TAG, Lazy.Ex.getStackTrace(e)); } return json; }
public static JSONObject postJsonObjectFromUrl(String url, Params params) { URL urlObject = null; try { urlObject = new URL(url); } catch (MalformedURLException e) { Log.e(TAG, Lazy.Ex.getStackTrace(e)); return jsonError("MalformedURLException"); } HttpURLConnection conn = null; try { conn = (HttpURLConnection) urlObject.openConnection(); } catch (IOException e) { Log.e(TAG, Lazy.Ex.getStackTrace(e)); return jsonError("IOException can't open connection"); } conn.setDoOutput(true); try { conn.setRequestMethod("POST"); } catch (ProtocolException e) { Log.e(TAG, Lazy.Ex.getStackTrace(e)); return jsonError("ProtocolException"); } PrintWriter out = null; try { out = new PrintWriter(conn.getOutputStream()); } catch (IOException e) { Log.e(TAG, Lazy.Ex.getStackTrace(e)); return jsonError("IOException can't get output stream"); } out.print(params.toUrlParams()); out.close(); try { int responseCode = conn.getResponseCode(); } catch (IOException e) { Log.e(TAG, Lazy.Ex.getStackTrace(e)); return jsonError("IOException can't get response code"); } String jsonString = ""; try { jsonString = getStringFromInputStream(conn.getInputStream()); } catch (Exception e) { Log.e(TAG, Lazy.Ex.getStackTrace(e)); } finally { conn.disconnect(); } try { return new JSONObject(jsonString); } catch (JSONException e) { Log.e(TAG, Lazy.Ex.getStackTrace(e)); return jsonError("JSONException"); } }