使用alamofire的https请求失败

时间:2019-08-30 22:37:27

标签: swift alamofire

我对快速编程非常陌生,所以这可能是愚蠢的错误。无论如何,当我执行要求HTTPS_REQUIRED althoge的url请求时,即使我在浏览器中手动检查了它的url字符串,我的代码也会失败

我尝试在plist文件中添加“应用程序传输安全设置”键,但它也不起作用。

func getImage(url : String){

    print(url)
    Alamofire.request(url, method: .get).responseJSON {
        response in
        if response.result.isSuccess {
            print(response.result.value)
        }
        else {
            print("Error \(response.result.error)")
            self.loadingLable.text = "Network Error"
        }
    }

}

//MARK:- Build the url request
func constructUrlRequest(latitude : String, longitude : String) {
    urlComponets.scheme = "https"
    urlComponets.host = "api.nasa.gov"
    urlComponets.path = "/planetary/earth/imagery"
    urlComponets.queryItems = [
        URLQueryItem(name : "lon", value : longitude),
        URLQueryItem(name : "lat", value : latitude),
        URLQueryItem(name: "api_key", value: "DEMO_KEY")
    ]
    let urlString = urlComponets.url?.absoluteString
    getImage(url: urlString!)

}

这是我的控制台输出:

longitude = -122.03051210999995, latitude = 37.33240904999999
https://api.nasa.gov/planetary/earth/imagery?lon=-122.03051210999995&lat=37.33240904999999&api_key=DEMO_KEY
Optional({
    error =     {
        code = "HTTPS_REQUIRED";
        message = "Requests must be made over HTTPS. Try accessing the API at: https://api.nasa.gov/planetary/earth/imagery/?lon=-122.03051210999995&lat=37.33240904999999&api_key=DEMO_KEY";
    };
})

1 个答案:

答案 0 :(得分:0)

您的代码是正确的,并且请求是通过https完成的,但是NASA API有点混乱。

只需检查API documentation,它就会重定向到def func(): def sub_func(): # repeatable code if not numpy.isnan(x[i][j]): print(f'X{x[i][j]}...') k = 0 for i in range(len(x)): if k % 2 == 0: # cut left to right, then right to left for j in range(len(x[i])): sub_func() else: for j in reversed(range(len(x[i]))): sub_func() k += 1 func() ,并且在请求中还需要其他变量。

尝试一下:

/planetary/earth/imagery/

输出:

   urlComponets.scheme = "https"
   urlComponets.host = "api.nasa.gov"
   urlComponets.path = "/planetary/earth/imagery/"
   urlComponets.queryItems = [
       URLQueryItem(name : "lon", value : "100.75"),
       URLQueryItem(name : "lat", value : "1.5"),
       URLQueryItem(name: "date", value: "2014-02-01"),
       URLQueryItem(name: "cloud_score", value: "True"),
       URLQueryItem(name: "api_key", value: "DEMO_KEY")
   ]