如何使用java访问github graphql API [英] how to access github graphql API using java

查看:166
本文介绍了如何使用java访问github graphql API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要访问 github graphql API 以获取有关某个存储库的某些数据。以下 curl 命令可以正常工作

I need to access the github graphql API to get some data about a certain repository. The following curl command is works fine

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 中调用相同的操作,因为我需要操作输出。这里是我试过的代码,

now I need to call the same in Java as I need to manipulate the outputs. Here is the code that I have tried,

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

}

当我调试代码时,它给我看这个错误,

When I debug the code, it showed me this error,


HttpResponseProxy {HTTP / 1.1 400 Bad Request [服务器:GitHub.com,日期:2017年2月3日星期五,12二月2017 12 :14:58 GMT,Content-Type: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:回购,X-GitHub-Media-Type:github.v3;格式= json,Access-Control-Expose-Headers:ETag,Link,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; includeSubdomains;预加载,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]}}

HttpResponseProxy{HTTP/1.1 400 Bad Request [Server: GitHub.com, Date: Fri, 03 Feb 2017 12:14:58 GMT, Content-Type: 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, user, X-Accepted-OAuth-Scopes: repo, X-GitHub-Media-Type: github.v3; format=json, Access-Control-Expose-Headers: ETag, Link, 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; includeSubdomains; preload, X-Content-Type-Options: nosniff, X-Frame-Options: deny, 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]}}

我做错了什么?你能不能帮我解决这个问题。
在此先感谢

what I am doing wrong? Can you please be kind enough to help me fix this. Thanks in advance

推荐答案

通过更改上面的代码来获取程序,如下所示。使用 JSON 库来创建像上面这样复杂的 JSON 是一个很好的习惯,除了手动创建它的时候,手动创建一个复杂的 JSON 可能会导致很多麻烦。

Got the program working by changing the above code as below. And it is a good practice to use a JSON library to create complex JSON like above other than manually creating it as most of the time, manual creation of a complex JSON may lead to lot of troubles.

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


    }

这篇关于如何使用java访问github graphql API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆