我正在使用 Django REST 框架。
@api_view(['POST'])
def image_params(request, format=None):
if request.method == 'POST':
print request.DATA
size = request.POST.get('size')
colour = request.POST.get('colour')
get_clothes = Clothes.objects.filter( Q(clothescolour=colour) | Q(clothessize=size))
serializer = ClothesSerializer(get_clothes, many=True)
result = serializer.data
print result
return Response(result,status=status.HTTP_201_CREATED)
我正在使用 POSTMAN 客户端发送 POST 请求,其中 form-data
中的 key
是 colour
且 value
是红色
。它工作完美,我得到了预期的结果。这是 print request.DATA
的样子:
<QueryDict: {u'colour': [u'red']}>
当我从 iOS 发送实际请求时,print request.DATA
看起来如图所示,并且我的过滤器查询失败。
{u'colour': u'red'}
以下是我在 iOS 中构造 HTTP Post 请求的方法:
NSDictionary* requestData = [NSDictionary dictionaryWithObjectsAndKeys:
@"red",
@"colour",
nil];
NSError *postError;
NSData *postData = [NSJSONSerialization dataWithJSONObject:requestData options:NSJSONWritingPrettyPrinted error:&postError];
[postRequest setHTTPMethod:@"POST"];
[postRequest setHTTPBody:postData];
[postRequest setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
我该怎么做才能让这项工作成功?
最佳答案
使用 POSTMAN,您可以发送表单数据,而使用 iOS,您可以发送 json 数据。
这就是为什么它的解析方式不同。
您需要在 POSTMAN 上设置 Content-Type: application/json
header 并发送原始数据:
{"color": "black"}
这样您将在两者上获得相同的字典格式。
关于ios - 来自 iOS 的 Django HTTP Post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18844322/