目标 c - 尝试将“原始”“应用程序/json”数据发布到服务器 API
Posted
技术标签:
【中文标题】目标 c - 尝试将“原始”“应用程序/json”数据发布到服务器 API【英文标题】:Objective c - trying to Post "raw" "application/json" data to server API 【发布时间】:2016-12-15 11:51:49 【问题描述】:我已经浏览了有关此主题的几篇帖子,但无法解决该问题。 - 我在邮递员中有以下结果:
通过 PostMan 发送的请求带有以下原始 - 应用程序/json 正文:
收到成功的响应:
但是,当我尝试使用以下代码进行相同的工作时
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";
【问题讨论】:
404 通常表示找不到 URL。你确定[NSURL URLWithString:HOME_VIEWS]
指向一个有效的网址吗?三重检查那个。
嗨,拉蒙——是的,它是正确的。我打印了 URL 并在浏览器上使用它,它工作正常。 POSTman 也使用相同的 URL
【参考方案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);
];
【讨论】:
以上是关于目标 c - 尝试将“原始”“应用程序/json”数据发布到服务器 API的主要内容,如果未能解决你的问题,请参考以下文章