使用Java中的Parse.com请求无效的JSON

时间:2015-09-16 11:41:54

标签: java json rest parse-platform request

我正在尝试将Parse的Curl REST API代码复制到Java中,如文档here所示:

curl -X GET \
-H "X-Parse-Application-Id: APPLICATION-ID" \
-H "X-Parse-REST-API-Key: REST-API-KEY" \
-G \
--data-urlencode 'where={"playerName":"Sean Plott","cheatMode":false}' \
https://api.parse.com/1/classes/GameScore

基本上,我试图根据所选用户的objectid在表项中找到用户的项目。

目前,我只是通过将我的程序作为Java应用程序运行来测试,但是我从响应中得到一个{“code”:107,“error”:“invalid JSON”}错误。我似乎无法得到卷曲的数据 - urlencode正确(或者它可能是我完全做错了)。如果重要,我正在使用OkHttp。

以下是我的代码:

public List<Item> getItemList(String user) {
    final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    String userID = getUserID(user);
    Gson gson = new Gson();

    System.out.println(userID);
    if(userID != null) {

        String json = "'where={\"Owner:\"" + userID + "\"}'";
        RequestBody reqBody = RequestBody.create(JSON, json );

        Request request = new Request.Builder()
        .url("https://api.parse.com/1/classes/Items")
        .header("Content-type", "application/json")
        .post(reqBody)
        .addHeader("X-Parse-REST-API-Key", REST_API_KEY)
        .addHeader("X-Parse-Application-Id", APPLICATION_ID)
        .build();

        Response resp;
        try {
            resp = client.newCall(request).execute();
            String html = resp.body().string();
            System.out.println("Html is: " + html);
        } catch (Exception e) {

        }

    } else {
        return null; //TODO: Throw no user found exception
    }
      return null;
}

它看起来很难看,但现在我只是想让它发挥作用。 getUserId()方法正常工作并返回正确的用户ID字符串。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我认为你不明白“--data-urlencode”选项对curl请求的作用。 curl行发送的请求看起来像编码版本:

encoded > https://api.parse.com/1/classes/GameScore?where=%7B"playerName"%3A"Sean%20Plott"%2C"c
decoded > https://api.parse.com/1/classes/GameScore?where={"playerName":"Sean Plott","cheatMode":false}

这是GET请求,如文档中所指定的,看起来您正在尝试发送POST请求。您是否尝试使用url-encoded数据发送GET请求?