如何从Java访问github graphql API而不在Java内部运行curl命令 [英] how to access the github graphql API from java without running curl commands inside java

查看:48
本文介绍了如何从Java访问github graphql API而不在Java内部运行curl命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请问我一个很长的问题,因为我是graphql的初学者.我需要访问github graphql API来获取某个文件上的责任详细信息,因为到目前为止,在此处中运行

Pardon me for the long question as I am a beginner to graphql. I need to access the github graphql API to get the blame details on a certain file, as upto now there is no blame REST API available in github API version 3. I can get output for the below graphql query which runs in here

  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命令

from running the following curl command in the terminal

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命令

and running the same curl command inside Java as below

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

}

还有其他方法可以在不运行curl命令的情况下在java中获得相同的输出,因为在java中运行curl命令不是一个好习惯(根据我的观点).预先感谢

is there any other way that I can get the same output in java without running curl commands, as running curl commands inside java is not a good practice (according to my view). Thanks in advance

使用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":解析JSON问题","documentation_url":" https://developer.github .com/v3 }

,但是当通过这样的简单查询String temp="{viewer {email login }}";时,它可以工作.我的代码有什么问题.请帮助

but when simple query like this is passed String temp="{viewer {email login }}"; it works. What is wrong with my code. Please help

推荐答案

这个问题与您添加了一个额外的查询"字样差不多,应该是 像这样的东西:

The issue is pretty much that you have added an extra "query" word, it should be something like this:

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

尽管我应该提醒您,您应该避免尝试对json进行硬编码,因此,理想的情况是您应该使用JSON库,从而产生以下内容(完整代码):

Although I should remind you that you should avoid trying to hardcode json as much as possible, therefore, the ideal scenario you should use a JSON library, resulting in something like this (full code):

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可以将其理解为单个字符串.

Take a note on how the escaped double quotes are just the ones so java can understand it as a single string.

这篇关于如何从Java访问github graphql API而不在Java内部运行curl命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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