2014-12-29 44 views
0

我有下面的curl命令可以很好地從我的Parse.com項目中檢索json對象列表。如何生成包含JSON的URL作爲GET操作的參數

curl -X GET -H "X-Parse-Application-Id: {MY_APP_ID}" -H "X-Parse-REST-API-Key: {MY_REST_API}" -H "X-Parse-Session-Token: {MY_SESSION_TOKEN}" -G --data-urlencode "where={\"$relatedTo\":{\"object\":{\"__type\":\"Pointer\",\"className\":\"_Role\",\"objectId\":\"{MY_OBJECT_ID}\"},\"key\":\"users\"}}" https://api.parse.com/1/users 

現在我想創建一個Java Servlet與HttpURLConnection做同樣的事情。我創建了以下網址:

String url = "https://api.parse.com/1/users?where={\"$relatedTo\":{\"object\":{\"__type\":\"Pointer\",\"className\":\"_Role\",\"objectId\":\"{MY_OBJECT_ID}\"},\"key\":\"users\"}}" 

URL object = new URL(strUrl); 

HttpURLConnection connection = (HttpURLConnection) object 
       .openConnection(); 

connection.setDoOutput(true); 
connection.setDoInput(true); 
connection.setRequestMethod("GET"); 
connection.setRequestProperty("X-Parse-Application-Id", APP_ID); 
connection.setRequestProperty("X-Parse-REST-API-Key", REST_API_KEY); 
connection.setRequestProperty("X-Parse-Session-Token", sessionToken); 
connection.setRequestProperty("Content-Type", "application/json"); 

然後我結束了得到一個錯誤:

java.lang.IllegalArgumentException: Illegal character in query at index 36: https://api.parse.com/1/users?where={"$relatedTo":{"object":{"__type":"Pointer","className":"_Role","objectId":"{MY_OBJECT_ID}"},"key":"users"}} 

我也有點相信它是拋出了錯誤的URL。但不知道如何解決它。謝謝!

+0

什麼是'str'以及它如何與'strUrl'相關?你也需要';'字符串文字後 –

回答

0

是必要的URL編碼,JSON內容:

這是一個實用程序,方法,你可以使用(例外不會拋出)。

static String urlEncode(String value) { 
    try { 
     return URLEncoder.encode(value, "UTF-8"); 
    } catch (UnsupportedEncodingException e) { 
     return value; 
    } 
} 

// ... in your code: 

String url = "https://api.parse.com/1/users?where=" 

url += urlEncode(
    "{\"$relatedTo\":{\"object\":{\"__type\":\"Pointer\",\"className\":\"_Role\",\"objectId\":\"{MY_OBJECT_ID}\"},\"key\":\"users\"}}" 
); 

我想你與真實ID替換{MY_OBJECT_ID}和您不要在一個JSON方式不編碼ID介紹下錯誤。在這種情況下,當您使用像Gsonorg.json這樣的JSON庫時,可以讓您的生活更輕鬆。

+0

這個工作。謝謝! – alextc

相關問題