【问题标题】:Swift GET request with json body带有 json 正文的 Swift GET 请求
【发布时间】:2018-08-02 20:03:00
【问题描述】:

我正在关注 API 文档,其中端点期望 GET 请求上的 JSON 正文。 curl示例如下:

curl -i -b /cookie.txt -H "Content-Type: application/json" -X GET -d "{\"groups\": [{\"groupId\":\"1\"} ],\"originatorId\":\"2\",\"schedule\":\"1234564334\",\"shortenedLink\":\"http://\",\"linkMessage\":\"点击在此被定向到\",\"messageTips\": [{\"date\": \"12/12/2018\",\"time\": \"16:00\",\"venue \": \"chelt\",\"赔率\": \"3/1\",\"betEntityName\": \"Dobbin\",\"bet\": \"10\",\"messageText \": \"Lorem ipsum dolor sit amet, consectetur adipiscing elit\"}, {\"date\": \"12/12/2018\",\"time\": \"17:00\",\ "地点\": \"york\",\"赔率\": \"3/1\",\"betEntityName\": \"Bobbin\",\"赌注\": \"20\",\ "messageText\": \"Lorem ipsum dolor sit amet, consectetur adipiscing elit\"}]}"

我在 swift 中使用以下代码,但服务器给出以下错误:

{"timestamp":1519328960600,"status":400,"error":"Bad Request","exception":"org.springframework.http.converter.HttpMessageNotReadableException","message":"要求的请求正文是缺少:公共 org.springframework.http.ResponseEntity

func test() {
    let requestUrl: URL = URL(string: "\(serverEP)/statistics")!

    var urlRequest = URLRequest(url: requestUrl)
    urlRequest.httpMethod = "GET"
    urlRequest.setValue("ID=\(defaults.string(forKey: "cookie")!)", forHTTPHeaderField: "Cookie")
    urlRequest.httpShouldHandleCookies = true
    urlRequest.timeoutInterval = 3

    let postString = "{\"groups\":\"test\"}"

    urlRequest.httpBody = postString.data(using: .utf8)

    let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
        if error == nil {
            if let data = data,
                let html = String(data: data, encoding: String.Encoding.utf8) {
                print(html)
            }
        }
    }
    task.resume()
}

如何在 GET 请求的正文中包含 JSON?

【问题讨论】:

  • 你不应该。当然,curl 让你这样做,但 URLSession 不会,因为在 GET 请求中未定义正文。如果您想在请求中包含正文,请执行POST。见stackoverflow.com/a/983458/1271826
  • 嗨 Rob,感谢您的回复,通常我会,但 API 不会接受 POST,有没有办法可以实现,因为我无法访问 API 源。
  • IIRC, URLSession 根本不会那样做。您应该与负责 Web 服务的团队交谈并让他们解决此问题。 (你 100% 确定它不会接受 POST 请求吗?这是非常奇怪的设计,我认为你必须扭曲自己才能不接受 POST 的 JSON 正文。)
  • 您好,谢谢您,我会看看他们是否会做出改变。我在 POST 时收到以下信息:“message”:“Request method 'POST' notsupported”,“path”:“/statistics”}
  • 好的,所以我猜它不会。 ;(希望网络服务团队可以帮助您...

标签: json swift get


【解决方案1】:

GET 请求没有正文,如果您在 GET 请求中使用正文,则表示您不遵守 HTTP 1.1 规范:

https://www.rfc-editor.org/rfc/rfc2616#section-4.3

https://www.rfc-editor.org/rfc/rfc2616#section-9.3

【讨论】:

    猜你喜欢
    • 2020-09-07
    • 2016-08-24
    • 1970-01-01
    • 2015-07-02
    • 2023-04-07
    • 2020-11-14
    • 2013-05-30
    • 2015-02-27
    • 2015-11-18
    相关资源
    最近更新 更多