2014-07-05 66 views
0

我想发送一个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 

我做错了什么?

回答

1

丹尼尔罗斯曼的回答让我有一半在那里:看request.body不是request.POST。其余的正确解码request.body,作为一个JSON序列化字典。

基本上,如上所述的客户端是好的。你只需要更改服务器,如下所示:

from django.utils import simplejson 

def myurl_view_func(request): 
    data = simplejson.loads(request.body) 
    key1 = data.get('key1', None) 
3

我对Objective-C一无所知,但是如果您序列化字典并将其发布为JSON,那么原始数据将在request.body而不是request.POST中找到。

+0

谢谢,丹尼尔,这是我所需要的一半。 (见下文)。非常感谢! – mobopro