目标c - 尝试将“原始”“application / json”数据发布到服务器API

时间:2016-12-15 11:51:49

标签: ios objective-c json

我已就此主题发表过几篇文章,但无法解决问题。 - 我在邮递员中有以下结果:

通过PostMan发送的请求包含以下Raw - application / json正文:

enter image description here

收到成功回复:

enter image description here

但是,当我尝试使用以下代码

进行相同的工作时
NSDictionary *postContent = @{ @"interests" : @"[\"TECHNOLOGY\",\"COOKING\",\"FINANCE\",\"SPORTS\",\"PHOTOGRAPHY\",\"FASHION\"]", @"user" : @"0", @"deviceId" : @"abcd", @"country_code" : @"IN" };

NSError *error = nil;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:postContent options:0 error:&error];

NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postdata length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:HOME_VIEWS]];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postdata];

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    NSLog(@"requestReply: %@", requestReply);
}] resume];

我总是在零字节数据时出现以下错误:

     { status code: 404, headers {
    Connection = close;
    "Content-Type" = "application/json; charset=utf-8";
    Date = "Thu, 15 Dec 2016 11:51:29 GMT";
    "Set-Cookie" = "JSESSIONID=B0FE830D979F7BFAD0DDA67AEB9E2999.views; Path=/proliphiq";
    "Transfer-Encoding" = Identity;
    "X-Powered-By" = "Servlet 2.5; JBoss-5.0/JBossWeb-2.1";
} }

1 个答案:

答案 0 :(得分:1)

导入“AFNetworking.h”

NSString *url = [NSString stringWithFormat:Url];
//NSDictionary *parameters = @{@"age": @(_age.intValue)};
NSDictionary *parameters = @{@"age": @(66)};

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject){


    NSLog(@"JSON--Age: %@", responseObject);
    NSDictionary *value = [responseObject objectForKey:@"data"];
    NSLog(@"JSON--Age-Stock: %@", [value objectForKey:@"stock"]);

} failure:^(NSURLSessionDataTask *task, NSError *error) {
    NSLog(@"Error--: %@", error);
}];