安卓如何使用HttpUrlConnect使用java查询Github graphql API
我不知道我的代码出了什么问题,当我尝试向GitHub发出请求时,我一直收到401错误。我的应用程序以前使用RESTAPI,我希望将其转换为Graphql,但我发现这很困难
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestProperty("Authorization","Bearer token");
urlConnection.setRequestProperty("Content-Type", "application/json");
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
wr.writeBytes("{\"query\":\"query{search(type:USER query:\"location:lagos language:java\"){userCount}}}");
wr.flush();
wr.close();
int rc = urlConnection.getResponseCode();
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
# 1 楼答案
我建议尝试使用Curl发出相同的请求,当您看到成功时,将相同的参数/头应用到HttpUrlConnection
# 2 楼答案
发现错误
我的令牌有问题,查询格式错误,应该是这样的
谢谢你的建议
# 3 楼答案
授权标头令牌可能无效。HTTP 401=未授权