1

I have trouble to send a JSON POST Request to my server.

My server accept a POST with application/json as type and an example would be like this:

{
  "name": "Group4",
  "users": [
     {"email": "[email protected]"},
     {"email": "[email protected]"},
  ]
}

If I send this by a REST client I get 200 OK as response, everything fine.

My Android client uses the Android Async HTTP Library (http://loopj.com/android-async-http/) and a documentation to the RequestParams class is here https://loopj.com/android-async-http/doc/com/loopj/android/http/RequestParams.html

RequestParams params = new RequestParams();
String userName = getUserName();
List<String> userList = getUserList();
params.put("name", userName);
JSONArray users = new JSONArray();
for(String user : userList) {
    JSONObject obj = new JSONObject();
    try {
        obj.put("email", user);
    } catch (JSONException e) {
        // ...
    }
    users.put(obj);
}
params.put("users", users);

I thought this will create exactly a JSON like my example. I don't know if I have the possibility to get a JSON string of this RequestParams. I only can access the parameter as a String:

name=Test&users=[{"email":"[email protected]"}, {"email":"[email protected]"}]

My server don't even accept the request and fails directly with the error:

AttributeError: 'unicode' object has no attribute 'iteritems'

The problem has to be at the point where I create the RequestParams. Can someone tell me what is wrong with that? I thought I have to create an array with name "users" and then add objects in it with key-value items.

2 Answers 2

3

Just put List<> to your RequestParams. Here is the example:

RequestParams params = new RequestParams();
List<String> list = new ArrayList<String>(); // Ordered collection

list.add("Java");
list.add("C");

params.put("languages", list); 

//above code will generate url params: "languages[0]=Java&languages[1]=C"

So you don't need to add it manually using Loop sequence. See the docs here

Sign up to request clarification or add additional context in comments.

Comments

-1

Will recommend to use Volley for Async calls in Android https://developer.android.com/training/volley/index.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.