Created
December 27, 2016 07:42
-
-
Save InventivetalentDev/f68b31cd8fffcb88d6b8a1de691311b5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.gson.JsonElement; | |
import com.google.gson.JsonParser; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.net.HttpURLConnection; | |
import java.net.URL; | |
public class Gson { | |
private static final String USER_AGENT = "MyUserAgent";// Change this! | |
private static final String REQUEST_URL = "https://api.spiget.org/v2/resources/12345"; | |
public static void main(String[] args) { | |
try { | |
URL url = new URL(REQUEST_URL); | |
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); | |
connection.addRequestProperty("User-Agent", USER_AGENT);// Set User-Agent | |
// If you're not sure if the request will be successful, | |
// you need to check the response code and use #getErrorStream if it returned an error code | |
InputStream inputStream = connection.getInputStream(); | |
InputStreamReader reader = new InputStreamReader(inputStream); | |
// This could be either a JsonArray or JsonObject | |
JsonElement element = new JsonParser().parse(reader); | |
if (element.isJsonArray()) { | |
// Is JsonArray | |
} else if (element.isJsonObject()) { | |
// Is JsonObject | |
} else { | |
// wut?! | |
} | |
// TODO: process element | |
System.out.println(element); | |
} catch (IOException e) { | |
// TODO: handle exception | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment