iOS和RestKit:如何获得文本/ HTML的回应权利?

我已经尝试了几个StackOverflow的问题,我开始find正确的答案。 我使用Chrome的POSTMAN插件来检查我的REST调用,我无法弄清楚为什么我不能读取响应。 在评论中,您将看到我为获得答复所做的所有不同尝试。

NSDictionary* session_params = @{SESSION_USERNAME_KEY:SESSION_USERNAME_VALUE, SESSION_PASSWORD_KEY:SESSION_PASSWORD_VALUE}; NSURL* url = [NSURL URLWithString:SESSION_URL]; RKObjectManager* objectManager = [RKObjectManager managerWithBaseURL:url]; //GET THE **** THING TO INTERPRET A TEXT response //[RKMIMETypeSerialization registerClass:[RKXMLReaderSerialization class] forMIMEType:RKMIMETypeTextXML]; //[objectManager setAcceptHeaderWithMIMEType:@"text/html"]; //[objectManager setAcceptHeaderWithMIMEType:RKMIMETypeTextXML]; //[RKMIMETypeSerialization registerClass:[RKXMLReaderSerialization class] forMIMEType:@"text/html"]; //[RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:@"text/html"]; //[objectManager setRequestSerializationMIMEType:@"text/html"]; //END NSMutableURLRequest* request = [objectManager requestWithObject:nil method:RKRequestMethodPOST path:SESSION_URL parameters:session_params]; RKObjectRequestOperation* operation = [objectManager objectRequestOperationWithRequest:request success:^(RKObjectRequestOperation* operation, RKMappingResult* result) { NSLog(@"RESULT [%@]", result); } failure:^(RKObjectRequestOperation *operation, NSError *error) { NSLog(@"ERROR [%@]", error); }]; [operation start]; 

我觉得最让人恼火的是,我需要的东西包含在NSLocalizedRecoverySuggestion的值中。 这是我需要的会话密钥。

OUTPUT:

E restkit.network:RKObjectRequestOperation.m:547对象请求失败:基础HTTP请求操作失败,出现错误:Error Domain = org.restkit.RestKit.ErrorDomain Code = -1016“Expected content type {(”application / x-www-form -urlencoded “ ”应用/ JSON“)},得到的text / html” 的UserInfo = {0x1c52aed0 = NSLocalizedRecoverySuggestion eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJCbG8uUmVnQWxlcnQuQnJva2VyIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdC9CbG8uUmVnQWxlcnQuQVBJL2FwaSIsIm5iZiI6MTM5MjY0MTY2MSwiZXhwIjoxMzkyNjQ1MjYxLCJ1bmlxdWVfbmFtZSI6IkJ1dHRvbnMiLCJyb2xlIjoiUmVnQWxlcnRDb25zdW1lciJ9.JCTMGJRKlOxEtNrcGodpce-tqsRS4zlApNisKQW6iSw,AFNetworkingOperationFailingURLRequestErrorKey =,= NSErrorFailingURLKey HTTP:// …,NSLocalizedDescription =预期的内容types{ (“application / x-www-form-urlencoded”,“application / json”)},得到text / html,AFNetworkingOperationFailingURLResponseErrorKey =} AppName [5600:6403] E restkit.network: RKObjectRequestOperation.m:213 POST'http:// …'(200 OK / 0 objects)[request = 0.0000s mapping = 0.0000s total = 0.1925s]:Error Domain = org.restkit.RestKit.ErrorDomain Code = -1016“Expected content type {(”application / x-www-form-urlencoded“ “应用/ JSON”)},得到的text / html “的UserInfo = {0x1c52aed0 = NSLocalizedRecoverySuggestion eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJCbG8uUmVnQWxlcnQuQnJva2VyIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdC9CbG8uUmVnQWxlcnQuQVBJL2FwaSIsIm5iZiI6MTM5MjY0MTY2MSwiZXhwIjoxMzkyNjQ1MjYxLCJ1bmlxdWVfbmFtZSI6IkJ1dHRvbnMiLCJyb2xlIjoiUmVnQWxlcnRDb25zdW1lciJ9.JCTMGJRKlOxEtNrcGodpce-tqsRS4zlApNisKQW6iSw,AFNetworkingOperationFailingURLRequestErrorKey =,= NSErrorFailingURLKey HTTP:// …,NSLocalizedDescription =预期的内容types{(” 应用/ x-www-form-urlencoded“,”application / json“)},得到text / html,AFNetworkingOperationFailingURLResponseErrorKey =}

代码工作感谢Wain 指引我在那里的正确的道路上。 我有点失望,RestKit无法处理这样一个简单的请求,我需要RestKit,因为这只是一个会话令牌调用其他方法,但无论我猜的工程:

 NSDictionary* session_params = @{SESSION_USERNAME_KEY:SESSION_USERNAME_VALUE, SESSION_PASSWORD_KEY:SESSION_PASSWORD_VALUE}; NSURL* url = [NSURL URLWithString:SESSION_URL]; AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:SESSION_URL parameters:session_params]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSString* response = [operation responseString]; NSLog(@"response: %@",response); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"error: %@", [operation error]); }]; [operation start]; 

这一点:

“预期的内容types{(”application / x-www-form-urlencoded“,”application / json“)},得到text / html”

告诉你,你已经告诉RestKit期望form-urlencodedjson ,但是服务器正在返回HTML。

您可能想要使用带有JSON MIMEtypes的setAcceptHeaderWithMIMEType来告诉服务器您想返回的内容。 但是,在这种情况下,你可能只是不应该使用RestKit。

RestKit用于将任意的JSON / XML数据映射到您的数据模型中。 你只是有一个关键回来。 不需要映射。 因此,不要使用RestKit,而应该使用AFNetworking(您可以完全访问它,因为RestKit在内部使用它)。

感谢Wain和Quintin,这对我非常有用:)

我认为在更新版本的RestkitAFNetworking有些名称已经改变。 我用AFNetworking解释在其他答案,因为服务器没有返回json而是空的plain/text 。 这只是在特定的端点上,我正在寻找响应标题中的一个标记。

在这里也分享我的一段代码:

 -(void) find_some_token_with_success:(void (^)(AFRKHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFRKHTTPRequestOperation *operation, NSError *error))failure { NSURL *baseURL = [NSURL URLWithString:@"https://example.com"]; AFRKHTTPClient *client = [AFRKHTTPClient clientWithBaseURL:baseURL]; [client setDefaultHeader:@"Accept" value:RKMIMETypeJSON]; [client setDefaultHeader:@"some_custom_header" value:@"some_custom_value"]; NSMutableURLRequest *request = [client requestWithMethod:@"GET" path:@"/api/v1/some_non_json_endpoint" parameters:nil]; AFRKHTTPRequestOperation *operation = [[AFRKHTTPRequestOperation alloc] initWithRequest:request]; [operation setCompletionBlockWithSuccess:success failure:failure]; [operation start]; } 

然后我用这样的东西来得到我正在寻找的标题:

 -(void) get_the_token:(void (^)(NSString *token))withTokenCallback failure:(void (^)(AFRKHTTPRequestOperation *operation, NSError *error))failure { [self xsrftoken_with_success:^(AFRKHTTPRequestOperation *operation, id responseObject) { NSString *token = [self get_the_token_from_response:[operation response]]; withTokenCallback(token); } failure:failure]; } -(NSString *) get_the_token_from_response: (NSHTTPURLResponse *) response; { NSDictionary *headerDictionary = response.allHeaderFields; NSString *token = [headerDictionary objectForKey:@"SOME-TOKEN-KEY"]; return token; } 

所以所有这些都可以简单的使用

 - (void)testGetSometokenInARequest { XCTestExpectation *expectation = [self expectationWithDescription:@"Query timed out."]; [[SomeRequestWithoutJsonResponse alloc] get_the_token:^(NSString *token) { [expectation fulfill]; NSLog(@"token: %@", token); // this token should be 100 characters long XCTAssertTrue([token length] == 100); } failure:^(AFRKHTTPRequestOperation *operation, NSError *error) { NSLog(@"error: %@", [operation error]); }]; [self waitForExpectationsWithTimeout:10.0 handler:nil]; } 

换句话说, get_the_token使用期望的令牌和失败callback进行callback。

确保你仍然包含<RestKit/RestKit>所以你有权访问Restkit的AFNetowkring 🙂


使用restkit的替代工作解决scheme:

RestKit:如何处理空的response.body?

你注册一个这样的Mimetype这样的序列化器:

 [RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:@"text/plain"];