【问题标题】:How to set HTTPBody?如何设置 HTTPBody?
【发布时间】:2015-06-05 20:19:22
【问题描述】:

在 Swift 中,我正在尝试发出一个发布请求(使用 NSURLSession)来让用户登录到 WebAPI 网络服务。

Url 是 www.myurltest.com/Token,我必须将以下字符串作为 POST 正文传递:

grant_type=password&username=MyUsername&password=MyPassword.

所以我在 Swift 中做了:

let session = NSURLSession.sharedSession();

let url = NSURL(string:"www.myurltest.com/Token");
let request = NSMutableURLRequest(URL: url!)
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"

现在我想设置 POST 正文(即字符串)但我不知道如何:

request.HTTPBody = ?????

谢谢。

【问题讨论】:

    标签: ios swift nsurlrequest


    【解决方案1】:

    你快到了,你只需要把字符串变成一个 NSData 对象。如果您的字符串位于名为body 的变量中,您的代码将类似于request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)

    【讨论】:

      猜你喜欢
      • 2013-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-06
      相关资源
      最近更新 更多