我使用以下代码通过NSURLSession
发布请求,但返回的结果不正确。但如果我用POSTMAN检查它有相同的参数和网址,那么它工作正常。请帮忙。
// URL of the endpoint we're going to contact.
NSURL *url = url;
// Create a simple dictionary with numbers.
NSDictionary *param = @{@"key1": @"value1"};
NSError *error = nil;
// Convert the dictionary into JSON data.
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:param
options:kNilOptions error:&error];
// Create a POST request with our JSON as a request body.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = JSONData;
// Create a task.
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error)
{
if (!error)
{
if (data) {
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
success(json);
}
else {
failure(error);
NSLog(@"******************* error in sendRequestToServer");
}
//NSLog(@"Status code: %i", ((NSHTTPURLResponse *)response).statusCode);
}
else {
failure(error);
NSLog(@"******************* error in sendRequestToServer");
}
}];
// Start the task.
[task resume];
答案 0 :(得分:0)
我首先设置Content-Type标头。大多数服务器根据内容类型以不同方式处理POST请求,并且您不能设置一个。