如何解决使用JDK11 HttpClient向GraphQL API发出POST请求
我的目标是将POST请求发送到GraphQL端点,然后返回它的输出消息。
在命令行中使用CURL查询GraphQL端点时,我已经成功获得响应。
但是,我现在正在尝试使用JDK11的HttpClient制作一个Java包来做同样的事情。
我的CURL请求是:
curl -XPOST https://example.com
-H "Content-Type:application/graphql" \
-H "x-api-key:KEY" \
-d '{"query":"query { start(type: \"generate\",name: \"test\",version: \"1\",stage: \"beta\") }"}'
这一直在起作用,并给了我预期的输出。
我现在的Java代码给了我这个错误。
{
"errors" : [ {
"message" : "Invalid JSON payload in POST request.","errorType" : "MalformedHttpRequestException"
} ]
}
我当前的Java代码是这样:
public void test() throws IOException,InterruptedException,IllegalArgumentException,URISyntaxException {
String API_KEY = "KEY";
String QUERY = "\"query { start(type: '\"generate'\",name: '\"test'\",version: '\"1'\",stage: '\"beta'\") }\"";
String API_URL = "https://example.com";
QUERY = QUERY.replaceAll("'","\\\\");
String API_REQUEST = "'{\"query\":" + QUERY + "}'";
//Make sure API_REQUEST is the same as the -d input in CURL
System.out.println(API_REQUEST);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(new URI(API_URL))
.header("Content-Type","application/graphql")
.header("x-api-key",API_KEY)
.POST(HttpRequest.BodyPublishers.ofString(API_REQUEST))
.build();
HttpResponse<String> httpResponse = client.send(request,HttpResponse.BodyHandlers.ofString());
System.out.println(httpResponse.statusCode());
String response = httpResponse.body();
System.out.println(response);
}
我打印出传递给HttpRequest POST方法的正文,以确保它与CURL请求中的正文完全相同,但是我仍然收到带有正文不正确的JSON格式消息的400错误代码。有谁知道导致此错误的原因以及我该如何解决?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。