簡體   English   中英

如何使用Java訪問github graphql API

[英]how to access github graphql API using java

我需要訪問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();
    }

}

當我調試代碼時,它向我顯示此錯誤,

HttpResponseProxy {HTTP / 1.1 400錯誤的請求[服務器:GitHub.com,日期:2017年2月3日,星期五,格林尼治標准時間12:14:58,內容類型:application / json; charset = utf-8,內容長度:89,狀態:400錯誤的請求,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; format = json,Access-Control-Expose-Header:ETag,鏈接,X-GitHub-OTP,X-RateLimit-Limit,X-RateLimit-Remaining,X-RateLimit-Reset,X-OAuth-Scopes,X-Accepted- OAuth范圍,X輪詢間隔,訪問控制允許來源:*,內容安全策略:default-src'none',嚴格傳輸安全性:max-age = 31536000; includeSubdomains; 預加載,X-Content-Type-Options:nosniff,X-Frame-Options:deny,X-XSS-Protection:1; 模式=塊,X-GitHub-Request-Id:CF0A:0EE1:B057F26:EBCB8DF:58947441] ResponseEntityProxy {[Content-Type:application / json; charset = utf-8,內容長度:89,已壓縮:false]}}

我做錯了什么? 您能幫我解決這個問題嗎? 提前致謝

通過更改以下代碼使程序正常工作。 與使用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();
        }


    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM