使用put和request body进行AFNetworking

时间:2014-10-07 14:34:11

标签: ios json afnetworking-2

我试图用身体发送,但作为回应,我有一个

JSON: {
errorr = "BAD json format";
success = 0;
}

我尝试使用与我的Rest Web Service Client代码中相同的字符串(json数组),它工作正常但不在我的应用程序中

NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys: carID, @"product_id", firstname.text, @"firstname", surname.text, @"lastname", phone.text, @"telephone", email.text, @"email", orderWithUserInfo, @"options", nil];
 NSLog(@"JSON: %@", dic);
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONReadingMutableContainers error:nil];
NSLog(@"JSON: %@", jsonData2);
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(@"jsonData as string:\n%@", jsonString);
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"34987598743" forHTTPHeaderField:@"X-Oc-Merchant-Id"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    AFHTTPRequestOperation *operationA = [manager PUT:@"http://***/api/rest/addorders" parameters:jsonString success:^(AFHTTPRequestOperation *operation, id responseObject) {

      NSLog(@"JSON: %@", responseObject);

        //[self showStream:carsList];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        // 4
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error"
                                                            message:[error localizedDescription]
                                                           delegate:nil
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil];
        [alertView show];
    }];

所以我不知道问题出在哪里

2 个答案:

答案 0 :(得分:1)

我已添加manager.requestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:dic];并解决了问题

答案 1 :(得分:0)

将参数作为NSDictionary传递,管理器将处理序列化。

  AFHTTPRequestOperation *operationA = [manager PUT:@"http://***/api/rest/addorders" parameters: dic success:^(AFHTTPRequestOperation *operation, id responseObject) { 


    }

PUT的方法签名是:

- (AFHTTPRequestOperation *)PUT:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void ( ^ ) ( AFHTTPRequestOperation *operation , id responseObject ))success failure:(void ( ^ ) ( AFHTTPRequestOperation *operation , NSError *error ))failure;

因此,您必须传递 NSDictioanry 而不是 NSString 。如果已初始化,请检查请求序列化程序。