0

这是对服务器的 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 not found

"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"]}

JSONArrayJSONObject其他地方放置或错误是正确的方法吗?

4

1 回答 1

1

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

你不调用toString()JSONArray你只是按原样传递它。

obj.put("ContentClassArr", ContentClassArr);

请参阅:JsonObject 的 Javadocs

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

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

于 2014-01-17T07:16:05.183 回答