[英]Anilist api v2 GRAPHQL
感謝您的高級幫助。
我正在一個需要我使用Anilist api v2的項目上工作,該版本使用graphQL
。 我已經嘗試了幾天,甚至連我大學的2位講師都沒有幫助,他們以前都沒有使用過graphql。
在下面發布的代碼中,我使用了來自另一個stackoverflow問題的HTTP POST
代碼,由於某種原因,我不斷收到響應代碼400
,這向我提示了某種語法錯誤。 我已經嘗試了多種格式的代碼,但是我還沒有偶然找到合適的格式,而且由於我對編程還很陌生,所以我無法真正理解github上的示例。
任何幫助表示贊賞,謝謝。
private static void aniList() {
try {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("https://graphql.anilist.co");
StringEntity entity = new StringEntity("\"query\": \"query { \n" +
" Media (id: 1, type: ANIME) { \n" +
" title {\n" +
" english\n" +
" }\n" +
" }\n" +
"}\", " +
"\"variables\": \"{}\"");
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.addHeader("Content-type", "application/json");
CloseableHttpResponse response = client.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
assert (statusCode == 200) : "response status code = " + statusCode + ", it's meant to be 200";
System.out.println("statusCode = " + statusCode);
client.close();
System.out.println(response.toString());
} catch (Exception exp) {
System.out.println("exception TRIGGERED");
System.out.println(exp.getMessage());
}
}
致未來的Google員工
try {
String json = "{\"query\":\"";
json += query;
json += "\"}";
json = json.replace("\n", " ").replace(" ", " ");
URL url = new URL(endpoint);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.addRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
os.write(json.getBytes("UTF-8"));
os.close();
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
in.close();
conn.disconnect();
return result;
} catch (Exception exp) {
System.out.println("exception TRIGGERED");
System.out.println(exp.getLocalizedMessage());
return "";
}
查詢示例:
query {
Media (search: "naruto", type: ANIME) {
id
title {
english
romaji
native
}
}
}
這對我來說效果很好,在我的問題中,我沒有正確格式化我認為的json,聽說json忽略了過多的空白和換行符,但我想不是嗎? json = json.replace("\\n", " ").replace(" ", " ");
出色地完成了這項工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.