import android.content.Context;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class JSONFunctions {
static JSONObject jObj;
static JSONArray jArray;
protected static String readResource (Context ctx, String filename) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader input = new BufferedReader(new InputStreamReader(ctx.getAssets().open(filename), "utf-8"), 8192);
String currLine;
while ((currLine = input.readLine()) != null) {
sb.append(currLine);
}
input.close();
return sb.toString();
}
public static JSONArray getJSONFromResource (Context ctx, String filename) throws IOException {
try {
String json = readResource(ctx, filename);
jArray = new JSONArray(json);
} catch (JSONException e) {
e.printStackTrace();
}
return jArray;
}
protected static String readURL (String url) throws IOException {
StringBuilder sb = new StringBuilder();
URL requestUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) requestUrl.openConnection();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"), 8192);
String line;
while ((line = input.readLine()) != null) {
sb.append(line);
}
input.close();
}
return sb.toString();
}
public static JSONObject getJSONFromURL (String url) throws IOException {
try {
String json = readURL(url);
jObj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
return jObj;
}
public static String HTTPGetFromKey (String apikey) throws IOException {
StringBuilder sb = new StringBuilder();
URL requestUrl = new URL("https://api.guildwars2.com/v2/account");
HttpURLConnection conn = (HttpURLConnection) requestUrl.openConnection();
conn.addRequestProperty("Authorization", "Bearer " + apikey);
conn.setAllowUserInteraction(false);
conn.setInstanceFollowRedirects(true);
conn.setRequestMethod("GET");
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"), 8192);
String line;
while ((line = input.readLine()) != null) {
sb.append(line);
}
input.close();
conn.disconnect();
}
return sb.toString();
}
public static JSONObject getJSONFromUserKey (String key) throws IOException {
try {
String json = HTTPGetFromKey(key);
jObj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
return jObj;
}
}