首页 文章

对Django服务器的iphone Json POST请求在QueryDict中创建QueryDict

提问于
浏览
6

我正在使用JSON库从Objective C创建一个JSON POST请求,如下所示:

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];

当我在Django视图中读取此请求时,调试器显示它占用了整个JSON字符串并使其成为POST QueryDict的第一个键:

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

我可以读取第一个键,然后使用JSON作为黑客重新解析 . 但为什么JSON字符串没有正确发送?

3 回答

  • 1

    我解决我的问题的残酷黑客是:

    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']
    

    所以这将允许我通过服务器端的额外步骤提取两个JSON值 . 但它应该一步到位 .

  • 0

    这是使用json数据处理POST请求的方法:

    def view_example(request):
        data=simplejson.loads(request.raw_post_data)
    
        #use the data
    
        response = HttpResponse("OK")
        response.status_code = 200
        return response
    
  • 3

    我已经处理过这个问题 . 我在阅读 request.body 字典时找到了一个临时解决方案 . 我假设你已经导入了 json/simplejson 库 . 在我看来:

    post = request.body
    post = simplejson.loads(post)
    foo = post["foo"]
    

    此代码块帮助我传递帖子问题 . 我认为在 request.POST 中发布 querydict 尚未在 NSMutableURLRequest 上正确开发 .

相关问题