简体   繁体   English

Swift 5:简单的字符串 URLRequest

[英]Swift 5: simple string URLRequest

I hope you can help me.我希望你能帮助我。

I am currently using native swift apis for URLSession and URLRequest network calls.我目前正在使用本机 swift apis 进行 URLSession 和 URLRequest 网络调用。

I have achieved the correct sending of json structures with the use of dictionaries.我已经使用字典实现了 json 结构的正确发送。

let params: [String: Any] = ["user": "demo"]
var request = URLRequest(url: URL(string: "https://.....")!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
do {
    request.httpBody = try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
  }catch _ {}

How would it be possible to send a simple string?怎么可能发送一个简单的字符串?

let params: "demo"
var request = URLRequest(url: URL(string: "https://.....")!)
request.httpMethod = "POST"
request.httpBody = .......?

您只需要使用data(using:)将字符串转换为Data

request.httpBody = "a simple string".data(using: .utf8)

你可以试试

request.httpBody = Data("yourString".utf8)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM