0

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

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

"Bearer token". Token is a placeholder, right? You need to get it from the service provider. Kind of like a password.
Yes, I have but still facing the same issue. And I do replace token with my access token
0

I'd suggest trying to make same request with a Curl and when you see success - apply same parameters/headers to HttpUrlConnection.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.