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

时间:2014-01-17 07:12:57

标签: android json http-post 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还是错误的正确方法?

1 个答案:

答案 0 :(得分:1)

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

您不会在toString()上致电JSONArray,只是按原样传递。

obj.put("ContentClassArr", ContentClassArr);

请参阅:Javadocs for JsonObject

那就是说,这不是你的问题。来自POST的404表示该URL不正确。但是,一旦使用了正确的URL,JSON就会成为一个问题。

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

相关问题