REST api 只有 1 个对象 java
REST api with only 1 object java
此代码使用 JSON-简单连接到 api:
try {
URL url = new URL("https://api.kanye.rest/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
int responsecode = conn.getResponseCode();
if (responsecode != 200) {
throw new RuntimeException("HttpResponseCode: " + responsecode);
} else {
String inline = "";
Scanner scanner = new Scanner(url.openStream());
while (scanner.hasNext()) {
inline += scanner.nextLine();
}
scanner.close();
//Using the JSON simple library parse the string into a json object
JSONParser parse = new JSONParser();
JSONObject data_obj = (JSONObject) parse.parse(inline);
JSONObject obj = (JSONObject) data_obj.get("quote");
commandSender.sendMessage("<Kanye> " + obj);
}
} catch (Exception e) {
e.printStackTrace();
}
不过什么也没有发出。唯一的警告是:
[15:15:49 WARN]: java.lang.ClassCastException: class java.lang.String cannot be cast to class org.json.simple.JSONObject (java.lang.String is in module java.base of loader 'bootstrap'; org.json.simple.JSONObject is in unnamed module of loader 'app')
[15:15:49 WARN]: at api-1.0.jar//net.ntdi.api.commands.kanyeCommand.perform(kanyeCommand.java:131)```
转换为字符串是解决方案。
String quote = (String) data_obj.get("quote")
此代码使用 JSON-简单连接到 api:
try {
URL url = new URL("https://api.kanye.rest/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
int responsecode = conn.getResponseCode();
if (responsecode != 200) {
throw new RuntimeException("HttpResponseCode: " + responsecode);
} else {
String inline = "";
Scanner scanner = new Scanner(url.openStream());
while (scanner.hasNext()) {
inline += scanner.nextLine();
}
scanner.close();
//Using the JSON simple library parse the string into a json object
JSONParser parse = new JSONParser();
JSONObject data_obj = (JSONObject) parse.parse(inline);
JSONObject obj = (JSONObject) data_obj.get("quote");
commandSender.sendMessage("<Kanye> " + obj);
}
} catch (Exception e) {
e.printStackTrace();
}
不过什么也没有发出。唯一的警告是:
[15:15:49 WARN]: java.lang.ClassCastException: class java.lang.String cannot be cast to class org.json.simple.JSONObject (java.lang.String is in module java.base of loader 'bootstrap'; org.json.simple.JSONObject is in unnamed module of loader 'app')
[15:15:49 WARN]: at api-1.0.jar//net.ntdi.api.commands.kanyeCommand.perform(kanyeCommand.java:131)```
转换为字符串是解决方案。
String quote = (String) data_obj.get("quote")