views:

291

answers:

3

I'm creating a JSON POST request from Objective C using the JSON library like so:

NSMutableURLRequest *request;
request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@/", host, action]]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json-rpc" forHTTPHeaderField:@"Content-Type"];
NSMutableDictionary *requestDictionary = [[NSMutableDictionary alloc] init];
[requestDictionary setObject:[NSString stringWithString:@"12"] forKey:@"foo"];
[requestDictionary setObject:[NSString stringWithString@"*"] forKey:@"bar"];

NSString *theBodyString = requestDictionary.JSONRepresentation;
NSData *theBodyData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];   
[request setHTTPBody:theBodyData];  
[[NSURLConnection alloc] initWithRequest:request delegate:self];

When I read this request in my Django view the debugger shows it took the entire JSON string and made it the first key of the POST QueryDict:

POST    QueryDict: QueryDict: {u'{"foo":"12","bar":"*"}': [u'']}>   Error   Could not resolve variable

I can read the first key and then reparse using JSON as a hack. But why is the JSON string not getting sent correctly?

A: 

My cruel hack to work around my problem is:

hack_json_value = request.POST.keys()[0]
hack_query_dict = json.loads(hack_json_value)
foo = hack_query_dict['foo']
bar = hack_query_dict['bar']

So this will allow me to extract the two JSON values with an extra step on server side. But it should work with one step.

MikeN
A: 

I've the same problem. Any news ¿?

Maybe is a problem with the GAE configuration. I've Python 2.6.6 with the last version of GAE. First of all, If I get the POST with a nc tool, the POST message is perfect:

POST /url/ HTTP/1.1 Accept: application/jsonrequest Content-type: application/json Accept-Encoding: gzip Content-Length: 458 Host: 192.168.1.1:8080 Connection: Keep-Alive

{"id":"xxx","jsonrpc":"2.0","method":"XXX","params":{...}]}

And in the server console I receive the next messages:

DEBUG 2010-09-16 06:47:05,891 dev_appserver.py:1693] Access to module file denied: /usr/lib/pymodules/python2.6/simplejson DEBUG 2010-09-16 06:47:05,894 dev_appserver.py:1700] Could not import "_json": Disallowed C-extension or built-in module DEBUG 2010-09-16 06:47:05,897 dev_appserver.py:1700] Could not import "_json": Disallowed C-extension or built-in module

And idea ¿? I supose the hack works perfectly, but I try to know where is the problem in order to prevent future problems ...

Thanks!

Iván Peralta
When I used the ASIHttp Library in my Xcode project I didn't have this problem so I moved to using that library for all requests from my iPad application.
MikeN
A: 

This is the way to process a POST request with json data:

def view_example(request):
    data=simplejson.loads(request.raw_post_data)

    #use the data

    response = HttpResponse("OK")
    response.status_code = 200
    return response 
mdrwxorg