我有一个奇怪的问题......我正在使用针对rails服务器的AFNetworking执行此ios http / json帖子,预期输出类似于:
{"success":true,"auth_token":"4D8CyUsyGZdqo6X1TCeq"}
有时它按预期工作,但通常在轨道方面,请求不会被检测为“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];
}];
答案 0 :(得分:0)
我知道我的服务,我需要添加application / jsonrequest以接受我的参数:
NSDictionary *parameter = @{@"email":@"philswenson@mymail.com", @"password":@"mypassword", @"accept:application/jsonrequest"};
AFJSONParameterEncoding仅告诉它在JSON文件中发送参数。我需要发送一个参数来告诉它如何发回数据。
答案 1 :(得分:0)
添加:
[httpClient setDefaultHeader:@"Accept" value:@"application/json"];
答案 2 :(得分:0)
我尝试了这些建议 - 没有骰子...... setDefaultHeader实际上导致了崩溃(无论iOS术语是否存在访问冲突)......
“accept:application / jsonrequest”}没有看到任何差异......
我最终使用了这段代码:
NSDictionary *parameter = @{@"email" : @"phil@gmail.com", @"password" : @"mypw", @"format":@"json"};