【发布时间】:2015-07-22 18:33:05
【问题描述】:
我正在使用此代码但无法正常工作。 NSLog in post 和 get 方法为空。 我需要发布原始数据。我在 Body - raw 中编写参数,它可以工作(Chrome- POSTMAN)。
这个参数:
[
{
"user": "admin",
"pass": "admin123",
"delete_book": 0,
"add_book": false,
"read_book": false,
"bookprice": 0,
"person": "",
"book": 0
}
]
我的 post 方法代码:
NSString * paramters = [[NSString alloc] initWithFormat:@"[{\"user\": \"admin\",\"pass\": \"admin123\",\"delete_book\": \"0\",\"add_book\": \"false\",\"read_book\": \"false\",\"bookprice\": \"0\",\"person\": \"\",\"book\": \"0\"}]"];
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:@"http://www.xxxxxxxxx.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
// NSData *postData = [NSJSONSerialization dataWithJSONObject:paramters options:0 error:&error];
NSData *postData = [paramters dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if([data length] > 0)
{
NSError *err = nil;
NSDictionary *dictResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];
NSLog(@"Result : %@",dictResponse);
}
else{
NSLog(@"Failed To Get Response.");
}
});
}];
[postDataTask resume];
我解决了问题 这是解决方案: NSData *postData = [参数 dataUsingEncoding:NSUTF8StringEncoding];
【问题讨论】:
-
发帖请求的格式是否正确?
-
我不知道,我知道我需要 JSON 发布请求。
-
我的意思是网址格式正确吗?
-
如我所见,您试图在 url.com 中发布没有意义的参数。
-
我的代码中有真实的 URL,这是示例。
标签: objective-c iphone json xcode post