使用json正文的Swift GET请求

时间:2018-02-22 20:15:34

标签: json swift get

我正在关注API文档,其中终点期望GET请求上的JSON正文。卷曲的例子如下:

  

curl -i -b /cookie.txt -H" Content-Type:application / json" -X GET -d" {\" groups \":[{\" groupId \":\" 1 \"}], \" originatorId \":\" 2 \",\" schedule \":\" 1234564334 \",\& #34; shortenedLink \":\" http:// \",\" linkMessage \":\"点击此链接指向\ ",\" messageTips \":[{\" date \":\" 12/12/2018 \",\&# 34;时间\":\" 16:00 \",\"场地\":\" chelt \",\&# 34;赔率\":\" 3/1 \",\" betEntityName \":\" Dobbin \",\&# 34;下注\":\" 10 \",\" messageText \":\" Lorem ipsum dolor sit amet,consectetur adipiscing elit \&# 34;},{\" 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& #34;:" org.springframework.http.converter.HttpMessageNotReadableException"," message":"缺少必需的请求正文:public 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?

1 个答案:

答案 0 :(得分:0)

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

https://tools.ietf.org/html/rfc2616#section-4.3

https://tools.ietf.org/html/rfc2616#section-9.3