簡體   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