-
-
Notifications
You must be signed in to change notification settings - Fork 1
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.
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();
}
}
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();
}
}
$USER_AGENT = "MyUserAgent";// Change this!
$REQUEST_URL = "https://api.spiget.org/v2/resources/12345";
$ch = curl_init($REQUEST_URL);
curl_setopt($ch, CURLOPT_USERAGENT, $USER_AGENT); // Set User-Agent
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$code = curl_getinfo($ch)["http_code"];
if ($code !== 200) {
// TODO: handle error code
}
curl_close($ch);
$data = json_decode($result, true);
// TODO: process data
print_r($data);