使用Swift在GET请求中使用额外的斜杠

时间:2018-06-05 22:39:10

标签: ios swift

我正在尝试发出GET请求。在URL的末尾配置了URL而没有斜杠。服务器在末尾接收带有“/”的URL,因此我得到错误404.我可以看到带有斜杠的response.url,但是urlRequest包含没有它的URL。

无法理解,发生了什么。

Meant to send:
http://someUrl.com/api

Sent:
http://someUrl.com/api/

代码示例

      guard let url = URL(string: self.rootUrl + "/api") else {
        print ("Can't make URL")
      return
    }
   var urlRequest = URLRequest(url: url)
    urlRequest.httpMethod = "GET"
    let sessionConf = URLSessionConfiguration.default
    let session = URLSession.init(configuration: sessionConf)

    let task = session.dataTask(with: urlRequest) {
        (data, response, error) in
        // check for any errors
        guard error == nil else {
            print("error calling GET on /api")
            print(error!)
            return
        }
        // make sure we got data
        guard let responseData = data else {
            print("Error: did not receive data")
            return
        }
        // parse the result as JSON, since that's what the API provides
        do {
            print (urlRequest)
            let json = try? JSONSerialization.jsonObject(with: responseData) as? [String: Any]
            if ( json == nil ) {
                print ("error json")
                print(response!)
            } else { ....

1 个答案:

答案 0 :(得分:0)

此请求的Swift缓存响应,将CachePolicy设置为忽略重新加载并尝试向其他网址执行GET请求,然后重试。