繁体   English   中英

如何使用HttpUrlConnect用Java查询Github graphql API

[英]How to query Github graphql API with java using HttpUrlConnect

我不知道我的代码有什么问题,当我尝试向GitHub发出请求时,我一直收到错误401。 我的应用程序之前使用REST API并将其转换为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;
}

发现错误

我的令牌存在问题,查询格式错误,应该是

"{\"query\": \"query { search ( type : USER, query : \\\"location:lagos\\\" ) { userCount }}\"}" 

谢谢你的建议

授权标头令牌可能无效。 HTTP 401 =未授权。

我建议尝试使用Curl发出相同的请求,当您看到成功时-将相同的参数/标头应用于HttpUrlConnection。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM