如何在下面的代码中发送带有正文的POST请求

时间:2019-07-19 06:23:16

标签: swift post alamofire

enter image description here

我需要使用JSON进行POST请求, 我提到了这个enter link description here

下面是我尝试过的代码。

let markURL = urls.studentListMark
let headers : HTTPHeaders = ["Authorization":"token" + " " + ProfileAuth]
let params = [
    "course":1,
    "batch":1
]
var urlComponent = URLComponents(string: markURL)!
let queryItems = params.map  { URLQueryItem(name: $0.key, value: $0.value as? String) }
print("queryItems ==   \(queryItems)")
urlComponent.queryItems = queryItems

let url  = URL(string: markURL)

var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: params)
request.allHTTPHeaderFields = headers

  Alamofire.request(request).responseJSON { response in
    //Your code
    if((response.result.value) != nil) {
        var jsonVar = JSON(response.result.value!)
        print("&&&&&&&&&")
        print(jsonVar)
    }
}

执行此方法时,没有响应。

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以将Alamofireparameters字段一起使用,如下所示:

let params = [
    "course": 1,
    "batch": 1
]

Alamofire.request(.POST, "http://YOURURL", parameters: params, encoding: .jsonEncoding).responseJSON { request, response, JSON, error in
    print(request)
    print(response)
    print(JSON)
    print(error)
}

我希望这是可行的。

享受。