我正在尝试使用类似
to this post which describes doing a PUT/POST for RESTful API的模式,但是对于GET.
我的原始代码看起来几乎相同,只是我使用了GET:关键字.我很快发现,而不是发送一个JSON主体,而是url编码参数.这在AFJSONSerializer类的文档中没有提到.您必须转到超类文档(AFHTTPSerializer)并读取其属性,您将在其中找到the one about HTTPMethodsEncodingParametersInURI.默认情况下,该组使用HEAD,GET和DELETE填充.那么对于那些类型的请求,JSON序列化器显然会恢复其父类的行为?
所以我把以下代码放在一起:
AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
manager.securityPolicy.allowInvalidCertificates = YES;
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet set];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername: currentUser() password: currentPassword()];
[manager
GET: @"https://172.16.214.214:44321/trees"
parameters: [NSDictionary dictionary]
success:^(NSURLSessionDataTask* task, id responseObject){
NSLog(@"Response: %@", responseObject);}
failure:^(NSURLSessionDataTask* task, NSError* error){
NSLog(@"Error: %@", error);}];
设置HTTPMethodsEncodingParametersInURI = [NSSet set]的行旨在让我获得JSON编码的参数,就像我想要的GET一样.不幸的是,当我使用它并在我的错误控制台中获取以下内容时,我在服务器上看不到任何内容:
2013-12-10 10:11:14.149 myValve[957:60b] Error: Error Domain=NSURLErrorDomain Code=-1005 "The
network connection was lost." UserInfo=0x17e5d4b0
{NSErrorFailingURLStringKey=https://172.16.214.214:44321/trees,
NSErrorFailingURLKey=https://172.16.214.214:44321/trees, NSLocalizedDescription=The network
connection was lost., NSUnderlyingError=0x17e53240 "The network connection was lost."}
我还缺少什么?
最佳答案 AFNetworking行为背后的基本原理可能是在Stack Overflow问题
HTTP GET with request body中最简洁地解释的.其中一个答案是
quotes Ray Fielding:
… In other words, any HTTP request message is allowed to contain a message body, and thus must parse messages with that in mind. Server semantics for GET, however, are restricted such that a body, if any, has no semantic meaning to the request. The requirements on parsing are separate from the requirements on method semantics.
So, yes, you can send a body with GET, and no, it is never useful to do so.
HTTP/1.1 spec将GET定义为“检索由Request-URI标识的任何信息(以实体的形式)”,并且不考虑将信息包括在请求的主体中.因此,在技术上可能不会禁止在GET请求中使用正文,但最好是非标准的. AFNetworking选择不支持它并不奇怪.
因此,您可能不希望将JSON放在GET请求的正文中.通常会将参数添加到URL.如果要在请求正文中发送JSON,请执行POST.