【问题标题】:NSMutableURLRequest Unsupported URLNSMutableURLRequest 不支持的 URL
【发布时间】:2018-04-23 01:48:32
【问题描述】:

我正在使用 Open Weather Map API 来获取用户当前的天气。

当我在 Postman 中运行请求时,我得到一个状态码 200 并且能够接收数据。但是,在 Xcode 中我得到错误 -1002

这是执行“GET”请求的代码:

// Configure URL String
NSString *apiKey = @"MY_API_KEY";
NSString *urlString = [[NSString alloc] initWithFormat:@"api.openweathermap.org/data/2.5/weather?APPID=%@&lat=%@&lon=%@", apiKey, latitude, longitude]; 
NSString *encodedUrl = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:encodedUrl];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];

[theRequest setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

[[session dataTaskWithRequest:theRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if(data != nil) {
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        NSLog(@"Here is the json dict: %@", jsonDict);
        NSLog(@"%@", response);
    }
    else {
        NSLog(@"error: %@", error);
    }
}] resume];

同样,这里的请求返回错误,但在 Postman 中我运行时没有收到错误:

api.openweathermap.org/data/2.5/weather?APPID=MY_API_KEY&lat=33.712926&lon=-117.839181

我如何设置请求有什么问题?

【问题讨论】:

    标签: ios objective-c openweathermap


    【解决方案1】:

    一个 URL 需要一个方案部分。请确保在 URL 字符串中包含诸如 httphttps 之类的协议:

    NSString *urlString = [[NSString alloc] initWithFormat:@"https://api.openweathermap.org/data/2.5/weather?APPID=%@&lat=%@&lon=%@", apiKey, latitude, longitude]; 
    

    【讨论】:

    • 我不敢相信我错过了这个。我早些时候尝试过,但失败了,因为我的请求无法通过“www”到达他们的服务器。添加。非常感谢您!
    • Kamchatka,这个“协议部分”被称为URL的“方案”。
    • @Rob 我不得不等待 8 分钟才能接受 - 被转移到一边但又回来接受!
    猜你喜欢
    • 2015-03-31
    • 1970-01-01
    • 2015-05-11
    • 2013-01-17
    • 1970-01-01
    • 2015-05-07
    • 2018-12-14
    • 1970-01-01
    相关资源
    最近更新 更多