Java tutorial
package com.andrious.btc.data; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.andrioussolutions.conn.HttpConn; import com.andrioussolutions.frmwrk.App; import com.andrioussolutions.frmwrk.settings.appSettings; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Iterator; import java.util.List; /** * Copyright (C) 2017 Greg T. F. Perry * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Created 14 Jun 2017 */ public class jsonUtils { private static String mErrorMsg = ""; public static double lastPrice(String url) { double lastPrice; try { lastPrice = Double.parseDouble(findKeyValue(getJSONj(url), "last")); } catch (Exception ex) { lastPrice = 0.0; } return lastPrice; } public static String getJSONj(String url) { StringBuilder result = new StringBuilder(); InputStreamReader stream = HttpConn.urlStream(url); try { BufferedReader reader = new BufferedReader(stream); String line; while ((line = reader.readLine()) != null) { result.append(line); } } catch (Exception ex) { result = new StringBuilder(); } finally { try { stream.close(); } catch (Exception ex) { } } return result.toString(); } public static String findKeyValue(String json, String keyValue) { String value = keyValue.trim(); String valueStr = ""; String nextValue; try { JSONObject obj = new JSONObject(json); Iterator<String> keys = obj.keys(); //To get keys of an object while (keys.hasNext()) { String key = keys.next(); if (key.contains(value)) { valueStr = obj.getString(key); break; } else { nextValue = obj.getString(key); // The value itself may be a json if (nextValue.indexOf(':') > 0) { valueStr = findKeyValue(nextValue, value); if (!valueStr.isEmpty()) { break; } } } } } catch (Exception ex) { valueStr = ""; } return valueStr; } public static List<?> getList(String url, TypeToken token) { List<?> list; InputStreamReader stream = HttpConn.urlStream(url); try { list = new Gson().fromJson(stream, token.getType()); } catch (Exception ex) { list = null; } finally { try { stream.close(); } catch (Exception ex) { } } return list; } public static Object getObj(String url, TypeToken token) { Object obj; InputStreamReader stream = HttpConn.urlStream(url); try { obj = new Gson().fromJson(stream, token.getType()); } catch (Exception ex) { obj = null; } finally { try { stream.close(); } catch (Exception ex) { } } return obj; } private static InputStreamReader urlStream(String url) { InputStreamReader input = null; // if (!App.isOnline()){ // // return input; // } try { input = getInputStream(url); } catch (Exception ex) { collectError(ex); // ErrorHandler.logError(ex); } return input; } private static InputStreamReader getInputStream(String urlString) throws IOException { HttpURLConnection conn = urlConnect(urlString); return new InputStreamReader(conn.getInputStream()); } private static HttpURLConnection urlConnect(String urlString) throws IOException { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); int response = conn.getResponseCode(); if (response != HttpURLConnection.HTTP_OK) { if (!handleResponse(response, conn)) { throw new RuntimeException("Failed : HTTP error code : " + response); } } return conn; } public static String getURL(String key, String defaultURL) { String urlString = appSettings.get(key, defaultURL); return urlString; } private static boolean handleResponse(int response, HttpURLConnection conn) { if (response == HttpURLConnection.HTTP_OK) { return true; } if (response == HttpURLConnection.HTTP_MOVED_TEMP || response == HttpURLConnection.HTTP_MOVED_PERM || response == HttpURLConnection.HTTP_SEE_OTHER) { String newURL = conn.getHeaderField("Location"); conn.disconnect(); try { // get redirect url from "location" header field and open a new connection again conn = urlConnect(newURL); return true; } catch (IOException ex) { throw new RuntimeException(ex); } } // Nothing to be done. Can't go any further. return false; } private static void collectError(Exception ex) { mErrorMsg = App.NoConnectivity(); if (mErrorMsg.isEmpty()) { String msg = ex.getMessage(); int index; if (msg == null) { index = 0; } else { index = msg.indexOf(":"); } if (index > 0) { mErrorMsg = msg.substring(0, index); if (mErrorMsg.indexOf("resolve") > 0 || mErrorMsg.indexOf("failed to connect") > 0) { mErrorMsg += "\nTry a different Exchange"; } } else { mErrorMsg = "Connection Timeout!"; //ex.getMessage(); } } } // Get the last error message public static String getError() { String msg = mErrorMsg; mErrorMsg = ""; return msg; } public static void onDestroy() { } }