如何写一个url字符串POST请求

时间:2017-11-21 21:15:49

标签: ios json swift xcode

嘿,所以我有一个网站,其中包含向其发布信息的文档。文档告诉如何发布。有这样的形式。

文档代码:

curl -X POST "https://api/management/user" \

-d "user_id=myuserid" \

-d "client=clientclientclient" \

-d "secret=secretsecret" 

我不知道如何用快速的字符串写出来。

代码:

let string = "https://api/management/user/user_id=myuserid/client=clientclientclient/secret=secretsecret"

然后我可以做这样的事情。

代码:

  let url = NSURL(string: string)
    let request = NSMutableURLRequest(url: url! as URL)
    request.httpMethod = "POST"
    let session = URLSession.shared
    let tache = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
    print(data!)
    print(response!)

    }

    tache.resume()

我很新。那么写这篇文章的正确方法是什么。

1 个答案:

答案 0 :(得分:2)

您需要将数据作为POST请求的HTTP正文发送。

if let theURL = URL.init(string:"https://api/management/user"{
   let request = URLRequest(url: theURL)
   request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
   request.httpMethod = "POST"
   let postString = "user_id=myuserid&client=clientclientclient&secret=secretsecret"
   if let encodedPostString = postString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed), let body = encodedPostString.data(using:.utf8){
      request.httpBody = body
   }
   let task = URLSession.shared.dataTask(with: request) { (data, response, error) -> Void in
      print(data!)
      print(response!)
    }
   task.resume()
}