【问题标题】:Get the HTTPURLResponse from a Siesta Response从 Siesta 响应中获取 HTTPURLResponse
【发布时间】:2025-12-10 13:20:03
【问题描述】:

我正在与执行 304 重定向的 REST API 作斗争;我需要的是获取重定向的目标 URL 并用浏览器打开它(我知道,这有点变态)。我成功拦截了重定向,多亏了这个可爱的小伙子 reversepanda: https://github.com/bustoutsolutions/siesta/issues/210 但是我还是没有弄清楚如何在GET请求的回调中获取重定向url(成功或失败)

resource.load().onSuccess{ response in
        //HERE I WOULD LIKE TO TAKE THE URL OF THE REDIRECT 
        //(if I print the response I can see the HTML of the destination web page where the user should land)
    }.onFailure{ error in
        //using 'completionHandler(nil)' in the 'willPerformHTTPRedirection' method of the delegate, brings me here
    }

关于如何解决此问题的任何建议?

谢谢!

【问题讨论】:

  • (1) 304 重定向??你是说301还是302?(2)Location头是不是没有出现在响应实体中?
  • 对不起,我的意思是 307(这是一个错字)。如何从标题中检索位置?如果我打印所有 response.headers,我看不到“位置”
  • Siesta 的 Entity 类型有一个 headers 属性。
  • 正确,当我说我正在打印“response.headers”时,这就是我所说的。但是在标题中我看不到位置

标签: swift siesta-swift


【解决方案1】:

看看 RequestChain.swift 里面,它有一些可以提供帮助的 cmets 示例。我相信您可以执行以下操作:

func redirectRequest() -> Request {
  return self.yourAnotherRequest(onSuccess: {
    }, onFailure: { error in
  })
}

func yourRequest(request: Siesta.Request) -> Request {
  return request.chained {
    guard case .failure(let error) = $0.response,
        error.httpStatusCode == 401 else {
            return .useThisResponse
    }

    return .passTo(
        self.redirectRequest().chained {
            if case .failure = $0.response {
                return .useThisResponse
            } else {
                return .passTo(request.repeated())
            }
        }
    )
  }
}

您可以在 Siesta 资源中使用关键字 chaineduseThisResponsepassTo 搜索更多示例。

如果它有助于解决您的问题,请告诉我们,很高兴看到您的最终解决方案。

【讨论】: