ios AFNetworking 和 POST 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12447725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 20:11:08  来源:igfitidea点击:

AFNetworking and POST Request

iosafnetworking

提问by Ans

I'm getting this response in error.userInfo while making a POST request from AFNetworking. Can anyone tell either I'm missing anything obvious or something need to fix at my server end?

在从 .userInfo 发出 POST 请求时,我在 error.userInfo 中收到此响应AFNetworking。谁能告诉我我遗漏了任何明显的东西还是需要在我的服务器端修复一些东西?

Request Failed with Error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Expected content type {( "text/json", "application/json", "text/javascript" )}, got text/html" UserInfo=0x6d7a730 {NSLocalizedRecoverySuggestion=index test, AFNetworkingOperationFailingURLResponseErrorKey=, NSErrorFailingURLKey=http://54.245.14.201/, NSLocalizedDescription=Expected content type {( "text/json", "application/json", "text/javascript" )}, got text/html, AFNetworkingOperationFailingURLRequestErrorKey=http://54.245.14.201/>}, { AFNetworkingOperationFailingURLRequestErrorKey = "http://54.245.14.201/>"; AFNetworkingOperationFailingURLResponseErrorKey = ""; NSErrorFailingURLKey = "http://54.245.14.201/"; NSLocalizedDescription = "Expected content type {(\n \"text/json\",\n \"application/json\",\n
\"text/javascript\"\n)}, got text/html"; NSLocalizedRecoverySuggestion = "index test"; }

请求失败,错误:错误域=AFNetworkingErrorDomain 代码=-1016“预期的内容类型{(“文本/json”,“应用程序/json”,“文本/javascript”)},得到文本/html” UserInfo=0x6d7a730 {NSLocalizedRecoverySuggestion=索引测试, AFNetworkingOperationFailingURLResponseErrorKey=, NSErrorFailingURLKey=http://54.245.14.201/, NSLocalizedDescription=预期的内容类型{( "text/json", "application/json", "text/javascript" )}, 得到 text/html, AFNetworkingOperationFailingURLRequestErrorKey =http://54.245.14.201/>}, { AFNetworkingOperationFailingURLRequestErrorKey = "http://54.245.14.201/>"; AFNetworkingOperationFailingURLResponseErrorKey = ""; NSErrorFailingURLKey = "http://54.245.14.201/" ; NSLocalizedDescription = "预期的内容类型 {(\n \"text/json\",\n \"application/json\",\n
\"text/javascript\"\n)}, got text/html"; NSLocalizedRecoverySuggestion = "index test"; }

And I'm using this code;

我正在使用此代码;

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient setDefaultHeader:@"Accept" value:@"application/json"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                        @"Ans", @"name",
                        @"29", @"age",
                        nil];

NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"/" parameters:params];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
    success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSLog(@"Success");
        NSLog(@"%@",JSON);

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
        NSLog(@"Failure");
}];

[operation start];
[operation waitUntilFinished];

回答by tarmelop

By default, AFJSONRequestOperationaccepts only "text/json", "application/json" or "text/javascript" content-types from server, but you are getting "text/html".

默认情况下,AFJSONRequestOperation只接受来自服务器的“text/json”、“application/json”或“text/javascript”内容类型,但你得到的是“text/html”。

Fixing on server would be better, but you can also add "text/html" content type as acceptable in your app:

在服务器上修复会更好,但您也可以在您的应用程序中添加“text/html”内容类型:

[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];

It worked for me, hope this helps!

它对我有用,希望这会有所帮助!

回答by Kjuly

Did you send this POST request by AFHTTPClient? If so, you need to set operation class for it:

您是否发送了此 POST 请求AFHTTPClient?如果是这样,您需要为其设置操作类:

AFHTTPClient * client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://localhost:8080"]];
// ...
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client setDefaultHeader:@"Accept" value:@"application/json"];
// ...

// EDIT: Use AFHTTPClient's POST method
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                         @"Ans", @"name",
                         @"29",  @"age", nil];

// POST, and for GET request, you need to use |-getPath:parameters:success:failure:|
[client postPath:@"/"
      parameters:params
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
           NSLog(@"RESPONSE: %@", responseObject);
           // ...
         }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
           if (error)
             NSLog(@"%@", [error localizedDescription]);
           // ...
         }

回答by yunas

Set your values in this code and check if it works for you

在此代码中设置您的值并检查它是否适合您

 AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:[NSURL URLWithString:kBASEURL]];
        NSString *_path = [NSString stringWithFormat:@"groups/"];
        _path = [_path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"%s %@",__PRETTY_FUNCTION__,_path);
        NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" 
                                                                path:_path
                                                          parameters:postParams];
        [httpClient release];

        AFJSONRequestOperation *operation = [AFJSONRequestOperation 
                                             JSONRequestOperationWithRequest:request
                                             success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
                                                 if ([JSON isKindOfClass:[NSArray class]] || [JSON isKindOfClass:[NSDictionary class]]) {
                                                     completed(JSON);
                                                 }
                                                 else {
                                                 }
                                                 [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];                                             

                                             } 
                                             failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
                                                 NSLog(@" response %@  \n error %@ \n JSON %@",response,error,JSON);
                                                 [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];                                         
                                                 errored(error);
                                             }];

        NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
        [queue addOperation:operation];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];