0

我有一个奇怪的问题...我正在使用 AFNetworking 针对 Rails 服务器执行此 ios http/json 帖子,预期的输出类似于:

{"success":true,"auth_token":"4D8CyUsyGZdqo6X1TCeq"}

有时它会按预期工作,但通常在 Rails 端,请求不会被检测为“JSON”请求,因此它提供 HTML。有人对此有想法吗?在设置 JSON 请求方面我做错了什么吗?

 NSDictionary *parameter = @{@"email":@"philswenson@mymail.com", @"password":@"mypassword"};
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://localhost:3000"]];
    [httpClient setParameterEncoding:AFJSONParameterEncoding];
    [httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];

    [httpClient postPath:@"api/v1/sessions" parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSString *jsonString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

        NSLog(@"Here is what we got %@", jsonString);
        NSDictionary *loginResult = [jsonString objectFromJSONString];
        NSNumber* success = [loginResult objectForKey:@"success"];
        NSLog(@"success = %@", success);
        NSLog(@"yay");
        // sample output:
        //  {"success":true,"auth_token":"4D8CyUsyGZdqo6X1TCeq"}

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self handleConnectionError:error];
    }];
4

3 回答 3

0

添加:

[httpClient setDefaultHeader:@"Accept" value:@"application/json"];

于 2013-09-04T08:54:46.187 回答
0

我尝试了这些建议 - 没有骰子...... setDefaultHeader 实际上导致了崩溃(无论 iOS 术语是什么访问冲突)......

“accept:application/jsonrequest”} 没有看到任何区别......

我最终使用了这段代码:

    NSDictionary *parameter = @{@"email" : @"phil@gmail.com", @"password" : @"mypw", @"format":@"json"};
于 2013-09-05T03:23:20.973 回答
0

我知道我的服务,我需要将 application/jsonrequest 添加到我的参数中,如下所示:

NSDictionary *parameter = @{@"email":@"philswenson@mymail.com", @"password":@"mypassword", @"accept:application/jsonrequest"};

AFJSONParameterEncoding 只告诉它在 JSON 文件中发送参数。我需要发送一个参数来告诉它如何发回数据。

于 2013-09-04T05:08:29.037 回答