NSURLSession请求返回404,但在Postman上运行良好。

时间:2021-04-01 18:55:50
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];

The code returns "The requested resource could not be found" 404 as response but when I try this request in my REST client (Postman) it works fine.

代码返回“不能找到请求的资源”作为响应,但是当我在REST客户机(Postman)中尝试这个请求时,它运行良好。

1 个解决方案

#1


0  

Try a url with the URLWithString method

尝试使用URLWithString方法的url。

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

#1


0  

Try a url with the URLWithString method

尝试使用URLWithString方法的url。

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