Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
943 views
in Technique[技术] by (71.8m points)

objective c - iphone Json POST request to Django server creates QueryDict within QueryDict

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...