2015-09-16 44 views
0

我試圖解析的捲曲REST API代碼複製到Java Parse.com請求如圖他們的文檔here在:無效JSON在Java

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 

本質上講,我試圖找到一個用戶的項表中的項目基於選定的用戶的目標。

目前,我只是通過運行我的程序作爲Java應用程序進行測試,但我得到了來自響應的{「code」:107,「error」:「invalid JSON」}錯誤。我似乎無法得到curl的數據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()方法正常工作並返回正確的用戶標識字符串。任何幫助,將不勝感激。

+0

你正在使用哪個requestBuilder實現?從Curl -X POST -d - > post.entity。但是,IMO Curl -X GET -G「編碼」 - > RequestBuilder.addParameters .... http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/方法/ RequestBuilder.html –

回答

0

我不認爲你已經理解了「--data-urlencode」選項對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請求?

+0

你是對的。那時我完全迷了路。最終,我能夠向Parse發送正確的GET請求。這也是我的編碼錯誤的事實。奇怪的是,OKHttp的HttpUrl.Builder()編碼似乎並不默認編碼大括號{},即使它們是RFC 1738不安全字符。 感謝您節省我的工作時間,Petter。 –