如何使用 java 访问 github graphql API

Posted

技术标签:

【中文标题】如何使用 java 访问 github graphql API【英文标题】:how to access github graphql API using java 【发布时间】:2017-06-20 19:40:14 【问题描述】:

我需要访问github graphql API 以获取有关某个存储库的一些数据。以下curl 命令运行良好

curl -i -H "Authorization: bearer myGithubToken" -X POST -d '"query": "query  repository(owner: \"wso2-extensions\", name: \"identity-inbound-auth-oauth\")  object(expression:\"83253ce50f189db30c54f13afa5d99021e2d7ece\")  ... on Commit  blame(path: \"components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzEndpoint.java\")  ranges  startingLine endingLine age commit  message url history(first: 2)  edges  node   message url    author  name email        "' https://api.github.com/graphql

现在我需要在Java 中调用相同的函数,因为我需要操纵输出。这是我尝试过的代码,

  public void callGraphqlApi()
    CloseableHttpClient httpClientForGraphql = null;
    CloseableHttpResponse httpResponseFromGraphql= null;

    httpClientForGraphql=HttpClients.createDefault();
    HttpPost httpPost= new HttpPost("https://api.github.com/graphql");

    String query= "query\":\"query  repository(owner: \"wso2-extensions\", name:\"identity-inbound-auth-oauth\")  object(expression: \"83253ce50f189db30c54f13afa5d99021e2d7ece\")  ... on Commit  blame(path: \"components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzEndpoint.java\")  ranges  startingLine endingLine age commit  message url history(first: 2)  edges  node  message url    author  name email        ";


    httpPost.addHeader("Authorization","Bearer myGithubToken");

    try 

        StringEntity params= new StringEntity(query);

        httpPost.addHeader("content-type","application/x-www-form-urlencoded");
        httpPost.setEntity(params);
        httpResponseFromGraphql= httpClientForGraphql.execute(httpPost);

     catch (UnsupportedEncodingException e) 
        // TODO Auto-generated catch block
        e.printStackTrace();
    


    catch (ClientProtocolException e) 
        // TODO Auto-generated catch block
        e.printStackTrace();
     catch (IOException e) 
        // TODO Auto-generated catch block
        e.printStackTrace();
    


当我调试代码时,它显示了这个错误,

HttpResponseProxyHTTP/1.1 400 错误请求 [服务器:GitHub.com,日期:格林威治标准时间 2017 年 2 月 3 日星期五 12:14:58,内容类型:application/json; charset=utf-8, Content-Length: 89, Status: 400 Bad Request, X-RateLimit-Limit: 200, X-RateLimit-Remaining: 187, X-RateLimit-Reset: 1486125149, X-OAuth-Scopes: repo,用户,X-Accepted-OAuth-Scopes:repo,X-GitHub-Media-Type:github.v3;格式=json,Access-Control-Expose-Headers:ETag,链接,X-GitHub-OTP,X-RateLimit-Limit,X-RateLimit-Remaining,X-RateLimit-Reset,X-OAuth-Scopes,X-Accepted- OAuth-Scopes, X-Poll-Interval, Access-Control-Allow-Origin: *, Content-Security-Policy: default-src 'none', Strict-Transport-Security: max-age=31536000;包括子域;预加载,X-Content-Type-Options:nosniff,X-Frame-Options:拒绝,X-XSS-Protection:1; mode=block, X-GitHub-Request-Id: CF0A:0EE1:B057F26:EBCB8DF:58947441] ResponseEntityProxy[Content-Type: application/json; charset=utf-8,Content-Length: 89,Chunked: false]

我做错了什么?请你好心帮我解决这个问题。 提前致谢

【问题讨论】:

我看起来您的 JSON 无效:应该以 String query= "\"query\":\"query 开头,而不是 String query= "query\":\"query 跨度> @peinearydevelopment 检查它仍然是同样的错误:( 【参考方案1】:

通过如下更改上述代码使程序正常工作。使用JSON 库来创建复杂的JSON 是一个很好的做法,而不是手动创建它,因为大多数时候手动创建复杂的JSON 可能会导致很多麻烦。

import org.json.JSONObject;

public void callingGraph()
        CloseableHttpClient client= null;
        CloseableHttpResponse response= null;

        client= HttpClients.createDefault();
        HttpPost httpPost= new HttpPost("https://api.github.com/graphql");

        httpPost.addHeader("Authorization","Bearer myToken");
        httpPost.addHeader("Accept","application/json");

        JSONObject jsonObj = new JSONObject();     
        jsonobj.put("query", "repository(owner: \"wso2-extensions\", name: \"identity-inbound-auth-oauth\")  object(expression: \"83253ce50f189db30c54f13afa5d99021e2d7ece\")  ... on Commit  blame(path: \"components/org.wso2.carbon.identity.oauth.endpoint/src/main/java/org/wso2/carbon/identity/oauth/endpoint/authz/OAuth2AuthzEndpoint.java\")  ranges  startingLine, endingLine, age, commit  message url history(first: 2)  edges  node   message, url    author  name, email        ");

        try 
            StringEntity entity= new StringEntity(jsonObj.toString());

            httpPost.setEntity(entity);
            response= client.execute(httpPost);

        

        catch(UnsupportedEncodingException e)
            e.printStackTrace();
        
        catch(ClientProtocolException e)
            e.printStackTrace();
        
        catch(IOException e)
            e.printStackTrace();
        

        try
            BufferedReader reader= new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String line= null;
            StringBuilder builder= new StringBuilder();
            while((line=reader.readLine())!= null)

                builder.append(line);

            
            System.out.println(builder.toString());
        
        catch(Exception e)
            e.printStackTrace();
        


    

【讨论】:

嗨,我在 Spring Boot 控制器中尝试了上述代码,但出现以下错误:HttpResponseProxyHTTP/1.1 500 Internal Server Error [X-Powered-By: Express, Access-Control-Allow-Origin: *, Date: Tue, 24 Apr 2018 10:01:35 GMT, Connection: keep-alive, Transfer-Encoding: chunked] ResponseEntityProxy[Chunked: true] 如何使用有效负载发出 GET 请求?由于 httpGet 对象没有 setEntity 方法,因此似乎无法调用 GraphQL API。

以上是关于如何使用 java 访问 github graphql API的主要内容,如果未能解决你的问题,请参考以下文章

如何查看除 master 以外的分支的 GitHub Contributors Graph?

如何查看除master以外的分支机构的GitHub Contributors Graph?

如何使用 java 访问 github graphql API

GitHub 在其 Graphs 页面上使用啥图形库?

如何使用 Java 的 Graph Class?

如何使用 Facebook Graph API 读取 Instagram 用户