AFNetworking 2.0的POST请求-AFHTTPSessionManager [英] POST request with AFNetworking 2.0 - AFHTTPSessionManager

查看:93
本文介绍了AFNetworking 2.0的POST请求-AFHTTPSessionManager的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,

我正在努力对REST解析API进行POST请求.我正在使用AFNetworking 2.0.我的AFHTTPSessionManager子类代码如下所示:

I am struggling with doing a POST request to the parse REST API. I am using AFNetworking 2.0. My code for the AFHTTPSessionManager Subclass looks as follows:

+ (ParseAPISession *)sharedSession {
     static ParseAPISession *sharedSession = nil;
     static dispatch_once_t onceToken;
     dispatch_once(&onceToken, ^{
         sharedSession = [[ParseAPISession alloc] initWithBaseURL:[NSURL URLWithString:kSDFParseAPIBaseURLString]];
    });
   return sharedSession;
}

并且:

- (id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (self) {
       [self.requestSerializer setValue:kSDFParseAPIApplicationId forHTTPHeaderField:@"X-Parse-Application-Id"];
       [self.requestSerializer setValue:kSDFParseAPIKey forHTTPHeaderField:@"X-Parse-REST-API-Key"];
   }

   return self;
}

我正在这样请求:

[[ParseAPISession sharedSession] POST:@"ClassName" parameters: [NSDictionary dictionaryWithObjectsAndKeys:@"name", @"name", nil] 
                              success:^(NSURLSessionDataTask *task, id abc) {
                                  NSLog(@"%@", abc);
                              } failure:^(NSURLSessionDataTask *task, NSError *error) {
                                  NSLog(@"%@", error);
}];

这样做我总是会遇到这种错误:

Doing this I always get this kind of error:

错误域= NSCocoaErrorDomain代码= 3840操作无法完成.(可可错误3840.)"(JSON文本未以数组或对象开头,并且未设置允许片段的选项.)UserInfo = 0x8c72420 {NSDebugDescription = JSON文本不是以数组或对象开头,并且没有允许设置片段的选项.}

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x8c72420 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

由于GET请求的工作方式像一个超级按钮,我很困惑为什么我无法发布某些内容.有人可以让我为这个问题欢呼吗?

Since the GET Request works like a charm I am quite confused why I can’t POST something. Can anybody halp me with this problem?

最诚挚的问候!

更新

经过大量测试后,此错误消息不再显示,不幸的是又出现了:

Happily after testing around a lot this Error message isn't displayed anymore, unfortuatelly another appeared:

<NSHTTPURLResponse: 0x8b96d40>
{ URL: https://api.parse.com/1/users }
{ status code: 400, 
headers {
    "Access-Control-Allow-Origin" = "*";
    "Access-Control-Request-Method" = "*";
    "Cache-Control" = "no-cache";
    Connection = "keep-alive";
    "Content-Length" = 130;
    "Content-Type" = "application/json; charset=utf-8";
    Date = "Wed, 30 Oct 2013 20:01:58 GMT";
    Server = "nginx/1.4.2";
    "Set-Cookie" = "_parse_session=BAh7BkkiD3Nlc3Npb25faWQGOgZFRiIlNjIxZjUxMzY3NWVhZWJmMDYyYWYwMGJiZTQ3MThmMWE%3D--851bd31b07e7dba2c5f83bb13a8d801ecbea42c4; domain=.parse.com; path=/; expires=Fri, 29-Nov-2013 20:01:58 GMT; secure; HttpOnly";
    Status = "400 Bad Request";
    "X-Runtime" = "0.060910";
    "X-UA-Compatible" = "IE=Edge,chrome=1";
} }

任何人都可以告诉我状态:400错误的请求"告诉我什么以及如何摆脱它吗?

Can anyone tell me what the Status: 400 Bad Request is telling me and how I can get rid of it?

推荐答案

此错误表示您的POST请求已通过,服务器成功向您返回了一些数据,而NSJSONSerialization在解析时遇到了麻烦.

This error means that your POST request went through, the server is successfully returning you some data, which NSJSONSerialization is having trouble parsing.

您可能需要设置AFJSONResponseSerializer以允许JSON片段.

You probably need to set your AFJSONResponseSerializer to allow JSON fragments.

AFHTTPSessionManager子类的init方法中:

AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
[self setResponseSerializer:responseSerializer];

如果这不起作用,则可能是编码方面的问题.从NSJSONSerialization类参考:

If this doesn't work, you probably have an encoding issue. From the NSJSONSerialization class reference:

数据必须采用JSON规范中列出的5种受支持的编码之一:UTF-8,UTF-16LE,UTF-16BE,UTF-32LE,UTF-32BE.数据可能有或没有BOM.用于解析的最有效编码是UTF-8,因此,如果可以选择对传递给此方法的数据进行编码,请使用UTF-8.

The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8.

检查服务器发送的编码类型.

Check the encoding type sent by your server.

最后,您可以在AFNetworking内部设置断点,也可以设置 AFNetworkActivityLogger ,该日志将记录请求将它们发送和接收到您的控制台.此工具对于调试此类问题非常有用.

Finally, you can either set breakpoints inside of AFNetworking, or set up AFNetworkActivityLogger, which will log requests as they are sent and received to your console. This tool is incredibly helpful for debugging this type of issue.

这篇关于AFNetworking 2.0的POST请求-AFHTTPSessionManager的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆