【问题标题】:How to query Github graphql API with java using HttpUrlConnect如何使用 HttpUrlConnect 使用 java 查询 Github graphql API
【发布时间】:2018-04-22 10:09:53
【问题描述】:

我不知道我的代码出了什么问题,当我尝试向 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;
}

【问题讨论】:

    标签: java android github httpurlconnection graphql


    【解决方案1】:

    发现错误

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

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

    感谢您的建议

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • “不记名令牌”。令牌是占位符,对吧?您需要从服务提供商处获取。有点像密码。
      • 是的,我有,但仍然面临同样的问题。我确实用我的访问令牌替换了令牌
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2017-06-20
        • 2018-08-25
        • 2018-02-08
        • 2018-08-25
        • 2017-02-01
        • 2018-06-23
        • 1970-01-01
        • 2022-08-02
        • 2017-12-27
        相关资源
        最近更新 更多