简体   繁体   中英

How to query Github graphql API with java using HttpUrlConnect

I don't know what is wrong with my code I keep getting error 401 when I try making a request to the GitHub. My app uses the REST API before now I and to convert it to the Graphql but I am finding it difficult

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;
}

Found the mistake

There was a problem with my token and the query format was wrong it should have been

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

Thank for your suggestion

The Authorization header token might not be valid. HTTP 401 = not authorized.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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