我想发送一个NSDictionary到我的Django服务器作为request.POST数据。我已经尝试了很多东西,并在这里看到类似的问题,但是他们都没有工作。下面是我对客户端:如何发布NSDictionary到Django服务器
NSString *url = @"http://mycompany.com/myurl";
NSDictionary *testDict = @{@"key1": @"value1", @"key2": @"value2"};
NSError *error;
if ([connectionController testPost:url dictionary:testDict returningResponse:&response error:&error]) {
NSLog(@"Success!");
}
的connectionController
对象有以下方法:
- (BOOL)testPost:(NSString *)url dictionary:(NSDictionary *)dict returningResponse:(NSDictionary **)response error:(NSError **)error {
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:error];
if (!data) {
return NO;
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:data];
NSURLResponse *urlResponse = nil;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:error];
if (*error) {
return NO;
}
*response = [NSJSONSerialization JSONObjectWithData:urlData options:NSJSONWritingPrettyPrinted error:error];
return YES;
}
而且在我的Django的服务器端:
def myurl_view_func(request):
print "request = %s" % request
key1 = request.POST.get('key1', None)
print "key1 = %s" % key1
但在执行时,服务器没有收到NSDictionary。相反,它打印:
request = <WSGIRequest
path:/myurl/,
GET:<QueryDict: {}>,
POST:<QueryDict: {}>,
...[snip]...
key1 = None
我做错了什么?
谢谢,丹尼尔,这是我所需要的一半。 (见下文)。非常感谢! – mobopro