NSURLSession请求返回404但在Postman上工作正常

时间:2017-11-15 12:26:39

标签: ios objective-c nsurlsession

NSString *URLString = @"http://api.sandbox.africastalking.com/version1/airtime/send";
NSString *encodedString = [URLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];

NSURL *url = [NSURL URLWithString:encodedString];

NSDictionary *body = @{
                       ...
                       };
// convert the dictionary into json data
NSError *error;
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];

// Create a post request with the json as a request body.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
request.HTTPBody = JSONData;

// create the task.
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    if (!error) {
        NSLog(@"Status code: %li", (long)((NSHTTPURLResponse *)response).statusCode);
        NSLog(@"Response: %@", response);

        NSString *responseText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"Response Text: %@", responseText);

    } else {
        NSLog(@"Error: %@", error.localizedDescription);
    }
}];
[task resume];

代码返回“找不到请求的资源”404作为响应,但是当我在我的REST客户端(Postman)中尝试此请求时,它可以正常工作。

1 个答案:

答案 0 :(得分:0)

尝试使用URLWithString方法

的网址
NSURL *url = [NSURL URLWithString:@"http://api.sandbox.africastalking.com/version1/airtime/send"];