[英]how to access the github graphql API from java without running curl commands inside java
因为我是graphql
的初学者, graphql
请问我一个长问题。 我需要访问github graphql API
来获取某个文件上的责任详细信息,因为到目前为止, github API版本3中还没有责任REST API
。 我可以获取以下在这里运行的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();
}
}
}
还有其他方法可以在不运行curl命令的情况下在java
获得相同的输出,因为在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”:“问题解析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可以将其理解为单个字符串。
@AdrianoMartins的答案是正确的,但是我只需修改该行就可以使我的程序正常工作
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-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 } } } } } } } }";
所以整个程序将是
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();
}
}
正如Adriano Martins还建议的那样,使用JSON
库比对JSON
硬编码更好
您还应该添加
responce.close()
根据此处的建议http://hc.apache.org/httpcomponents-client-4.4.x/tutorial/html/fundamentals.html#d5e145
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.