Skip to content

Request Code Examples

Haylee Schäfer edited this page Dec 27, 2016 · 6 revisions

This is a collection of code snippets on how to make requests to the Spiget API. Please note that all of these send custom User-Agent headers, as it is recommended in the API documentation.

Java

Gson (recommended)

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();
	}
}

(full code)

JSON API

private static final String USER_AGENT  = "MyUserAgent";// Change this!
private static final String REQUEST_URL = "https://api.spiget.org/v2/resources/2";

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
		Object value = JSONValue.parseWithException(reader);

		// TODO: process value
		System.out.println(value);
	} catch (IOException | ParseException e) {
		// TODO: handle exception
		e.printStackTrace();
	}
}

(full code)

Clone this wiki locally