在POST请求中将JSONArray放入JSONObject时出现的问题



这是对服务器-的POST请求

public String callServiceTotalRecords(String userName, String password, String email, String type, String start, String end, String userTimeZone, JSONArray ContentClassArr)
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(WEBSERVICE + type);
HttpResponse response = null;
String responseBody = "";
try {
String base64EncodedCredentials = "Basic " + Base64.encodeToString( 
(userName + ":" + password).getBytes(), 
Base64.NO_WRAP);

httppost.setHeader("Authorization", base64EncodedCredentials);
httppost.setHeader(HTTP.CONTENT_TYPE,"application/json");
JSONObject obj = new JSONObject();
obj.put("Start", start); 
obj.put("End", end);
obj.put("emailId", email);
obj.put("userTimeZone", userTimeZone);
obj.put("ContentClassArr",ContentClassArr.toString());
httppost.setEntity(new StringEntity(obj.toString(), "UTF-8"));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == 200) 
{
responseBody = EntityUtils.toString(response.getEntity());
Log.d("response ok", "ok response :/");
} 
else 
{
responseBody = "";
Log.d("response not ok", "Something went wrong :/");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
return responseBody;
}              

但是响应是404未找到

"response not ok: Something went wrong"

怀疑的是ContentClassArr,它是像-一样形成的JSONArray类型

JSONArray ContentClassArr= new JSONArray("["UserLog","Sheets"]");

然后我把它放在JSONObject中,就像-一样

obj.put("ContentClassArr",ContentClassArr.toString());

服务器上典型的正确json应该是-

{"emailId":"usertest@gmail.com","Start":"2014-01-09T12:51:34.110Z","userTimeZone":"America/Los_Angeles","End":"2014-01-16T12:51:34.110Z","ContentClassArr":["UserLog","Sheets"]}

这是将JSONArray置于JSONObject的正确方法吗?或者错误在其他地方?

obj.put("ContentClassArr",ContentClassArr.toString());

您不在JSONArray上调用toString(),只需按原样传递即可。

obj.put("ContentClassArr", ContentClassArr);

请参阅:JsonObject 的Javadocs

也就是说,这不是你的问题。POST中的404表示URL不正确。然而,一旦使用了正确的URL,JSON就会成为一个问题。

另外,请不要使用大写的变量名。它违反了命名约定,使您很难阅读代码。类名是大写的,变量不是。

最新更新