繁体   English   中英

如何使用 okHttpClient 执行 graphql 查询?

[英]How to excute graphql query with okHttpClient?

我有这个正在处理 postman 的查询

    query  {
getInstallment(amount: "400", bin: "400000", userName: "guille") {
    cardBrand
}
}

但是当我尝试使用 okHttpClient 执行此有效负载时

    OkHttpClient client = new OkHttpClient();

    MediaType mediaType = MediaType.parse("application/graphql");
    RequestBody body = RequestBody.create(mediaType, "query  {\n" +
            "getInstallment(amount: \"400\", bin: \"400000\", userName: \"sbernal\") {\n" +
            "    cardBrand\n" +
            "}}");
    Request request = new Request.Builder()
            .url("https://awsendpoint.appsync-api.us-east-1.amazonaws.com/graphql")
            .post(body)
            .addHeader("x-api-key", "dket")
            .build();

    Response response = client.newCall(request).execute();
    System.out.println(response.code());

}

    OkHttpClient client = new OkHttpClient();

    MediaType mediaType = MediaType.parse("application/graphql");
    RequestBody body = RequestBody.create(mediaType, "query  {\n" +
            "getInstallment(amount: \"400\", bin: \"400000\", userName: \"guille\") {\n" +
            "    cardBrand\n" +
            "}}");
    Request request = new Request.Builder()
            .url("https://ziexbkvj5bghnnyicsbge737oa.appsync-api.us-east-1.amazonaws.com/graphql")
            .post(body)
            .addHeader("x-api-key", "da2-7utq5lkg5zcllodmlzp66dd3vy")
            .build();

    Response response = client.newCall(request).execute();
    System.out.println(response.code());



}}

我收到错误 400,我做错了什么? 我应该使用另一个 httpclient 吗?

可能存在 2 个问题(+ 1 个弃用和 1 个注释):

  1. 我在 appsync 中成功使用了“application/json”(但我没有尝试使用“application/graphql”):
    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
  1. 正文的内容必须是 Json 序列化字符串:
RequestBody body = RequestBody.create(mediaType, "{ \"query\": \"query  {\n" +
            "getInstallment(amount: \"400\", bin: \"400000\", userName: \"sbernal\") {\n" +
            "    cardBrand\n" +
            "}} }");
  1. RequestBody.create used 现在已弃用,但您可以将 Json 字符串作为第一个参数来删除弃用警告。

  2. 为了完整起见,请注意 Json Object [查询、操作名称和变量]中提供了几个键,例如:

        JsonObject json = new JsonObject();
        json.addProperty("query", "mutation CreateAccount($name: String!) {\n"
        + "  createAccount(input: {name: $name}) {\n"
        + "    id\n"
        + "  }\n"
        + "}");
        json.addProperty("operationName", "CreateAccount");
        JsonObject variables = new JsonObject();
        variables.addProperty("name", "account1");
        json.add("variables", variables);
        
        RequestBody body = RequestBody.create(json.toString(), JSON);

我正在探索类似的事情并遇到了这个问题,因为我能够使用OKHttp Client 来完成它并且它相当简单,我想在这里发布代码以供其他人使用以使其更容易做到。

我们可以使用 OKHttp Client 使用以下步骤模拟它

  • 初始化 OKHttp 客户端
  • Jsonify 查询字符串
  • 创建 Json 对象并初始化它们,如果我们想传递任何参数值,就像在这个例子中我发送 cursor 值。
  • 通过使用必要的属性对其进行初始化来创建请求主体
  • 使用 OkHttp 客户端实例执行请求。
  • 获取 Json Response 并使用.string()方法而不是.toString()方法来存储 json Response。

请在下面找到从Heroku App获取太空船发射列表详细信息的代码

public String getResponse() {
    
    String response = "";
    OkHttpClient client = new OkHttpClient();

    try {
   
        String json = "query LaunchList($cursor: String) {\n"
        +"launches(after: $cursor) {\n"
        +    "cursor\n"
        +            "hasMore\n"
        +    "launches {\n"
        +        "id\n"
        +                "site\n"
        +        "mission {\n"
        +            "name\n"
        +            "missionPatch(size: SMALL)\n"
        +        "}\n"
        +    "}\n"
        +"}\n"
    +"}";


        jsonObject.put("query",json);
        JSONObject variables = new JSONObject();
        variables.put("cursor","");
        jsonObject.put("variables",variables);

        RequestBody requestBody = RequestBody.create(jsonObject.toString(), MediaType.parse("application/json; charset=utf-8"));
    Request request = new Request.Builder()
            .url("https://apollo-fullstack-tutorial.herokuapp.com/graphql")
            .post(requestBody)
            .build();

        response = client.newCall(request).execute().body().string();
    } catch (IOException ioException) {
        System.out.println(ioException.toString());
    }
    return response;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM