java - 如何在不在 java 中运行 curl 命令的情况下从 java 访问 github graphql API

标签 java github graphql

请原谅我问这么长的问题,因为我是 graphql 的初学者。我需要访问 github graphql API 来获取某个文件的 blame 详细信息,因为到目前为止,github API version 3 中没有可用的 blame REST API .我可以获得在 here 中运行的以下 graphql 查询的输出

  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
              }
            }
          }
        }
      }
    }
  }
}

在终端中运行以下 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 中运行相同的 curl 命令,如下所示

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Demo {
    public static void main(String[] args) {

        String url="https://api.github.com/graphql";
           String[] command = {"curl", "-H" ,"Authorization: Bearer myGitHubToken","-H","Accept:application/json","-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 } } } } } } } }\"}" , url};
            ProcessBuilder process = new ProcessBuilder(command); 
            Process p;
            try
            {
                p = process.start();
                 BufferedReader reader =  new BufferedReader(new InputStreamReader(p.getInputStream()));
                    StringBuilder builder = new StringBuilder();
                    String line = null;
                    while ( (line = reader.readLine()) != null) {
                            builder.append(line);
                            builder.append(System.getProperty("line.separator"));
                    }
                    String result = builder.toString();
                    System.out.print(result);

            }
            catch (IOException e)
            {   System.out.print("error");
                e.printStackTrace();
            }
    }

}

有没有其他方法可以在 java 中获得相同的输出而无需运行 curl 命令,因为在 java 中运行 curl 命令是这不是一个好的做法(根据我的观点)。提前致谢

使用 httpClient 代码更新

这是我用 apache httpClient 尝试的代码

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");


        String temp="{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 } } } } } } } }";

//        String temp="{repository(owner:\"wso2\",name:\"product-is\"){description}}";

        try {

           StringEntity entity= new StringEntity("{\"query\":\"query "+temp+"\"}");

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


    }

但即使是 {repository(owner:\"wso2\",name:\"product-is\"){description}} 的小查询,它也会给我

{"message":"Problems parsing JSON","documentation_url":"https://developer.github.com/v3"}

但是当传递像这样的简单查询时 String temp="{viewer {email login }}"; 它起作用了。我的代码有什么问题。请帮忙

最佳答案

问题是你添加了一个额外的“查询”字,应该是 像这样:

(...)
StringEntity entity= new StringEntity("{\"query\":\""+temp+"\"}");

尽管我应该提醒您,您应该尽可能避免尝试对 json 进行硬编码,因此,理想情况下您应该使用 JSON 库,从而产生类似这样的结果(完整代码):

import org.json.JSONObject; // New import

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 将其理解为单个字符串的。

关于java - 如何在不在 java 中运行 curl 命令的情况下从 java 访问 github graphql API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42063825/

相关文章:

java - 使用扩展Swing组件,线程疑问

github - 如何在 git 存储库中执行 "find and replace"?

javascript - 如何修复数据类型关系导致的 'Variable "$_v0_data“得到无效值” - Mutation Resolver

java - 如果用户不接受条款,则关闭应用程序的按钮

java - Thread.sleep 显然不会强制上下文切换

git - macOS Sierra 更新后无法同步 git

R Studio - 由于空提交消息而中止提交 - 使用 blogdown 部署时

graphql - 变量 $varname 未出现在任何 graphQL 查询中

node.js - graphql prisma nodejs postgresql 如何将创建日期/更新字段添加到 graphql 类型?

java - 如何在不填写字段的情况下获取消息的文本格式