使用AFHttpRequestOperationManager发布请求不起作用

Sha*_*jan 14 ios7 afnetworking-2

我正在使用AFHTTPRequestOperationManager将一些JSON发布到我的服务器,我的代码如下.

NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:@"john", @"name", @"xxxxx@gmail.com", @"email", @"xxxx", @"password", @"1", @"type", nil];
// Do any additional setup after loading the view.
AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
[policy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager setSecurityPolicy:policy];

[operationManager POST:@"posturl here" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", [responseObject description]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", [error description]);
}];
Run Code Online (Sandbox Code Playgroud)

响应如下:

2013-11-18 16:49:29.780 SwapOnceApiTester[12651:60b] Error: Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: unsupported media type (415), got 1664256" UserInfo=0x1565a6c0 {NSErrorFailingURLKey=xxxxxxx, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x15656db0> { URL: xxxxxxxxx } { status code: 415, headers {
    "Cache-Control" = "max-age=604800";
    Connection = "keep-alive";
    "Content-Type" = "application/json";
    Date = "Mon, 18 Nov 2013 11:49:28 GMT";
    Expires = "Mon, 25 Nov 2013 11:49:28 GMT";
    Server = nginx;
    "Transfer-Encoding" = Identity;
    "X-Powered-By" = PleskLin;
} }, NSLocalizedDescription=Request failed: unsupported media type (415), got 1664256}
Run Code Online (Sandbox Code Playgroud)

我不知道这个问题是什么.

Ral*_*nso 29

您需要设置请求和响应序列化程序,以便在执行请求之前AFJSONRequestSerializerAFJSONResponseSerializer之前处理JSON .为参数使用NSDictionary文字也有助于代码清晰度:

AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
[policy setAllowInvalidCertificates:YES];

AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager setSecurityPolicy:policy];
operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
operationManager.responseSerializer = [AFJSONResponseSerializer serializer];

[operationManager POST:@"posturl here" 
            parameters: @{@"name":  @"john",
                        @"email":   @"xxxxx@gmail.com",
                        @"password: @"xxxxx",
                        @"type":    @"1"}
               success:^(AFHTTPRequestOperation *operation, id responseObject) {
                   NSLog(@"JSON: %@", [responseObject description]);
               } 
               failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                   NSLog(@"Error: %@", [error description]);
               }
];
Run Code Online (Sandbox Code Playgroud)


Sha*_*jan 0

只是解决我的问题,我的服务器没有配置为接受 application/json 的字符集 utf8,所以我刚刚删除了 Afnetworking 2.0 中 ajson 序列化程序的字符集 utf,现在它可以正确工作。

  • 您能否更具体一些 - 您在哪里删除了以及删除了什么? (6认同)