swift4 - 如何在没有 alamofire 的 swift 4 中使用 rawdata 在正文中发送字符串?
问题描述
{
"1":[{"name":"some product","type":"simple","quantity":"2","price":"500"}],
"2":[{"name":"Seller 2 add no 2","type":"feature","quantity":"1","price":"500"}],
"is_free_quota":"0",
"quotationIsVerified":"0"
}
这是我必须发送的字符串
解决方案
//在这个函数中,我们发送令牌进行身份验证,数据以原始数据形式发送......没有参数和没有alamofire
func postRequest() -> 无效){
let parameters = [""]
let url = URL(string: "http://192.168.10.7/retbajri/public/api/request/quot")!
print(url)
let user1 = ["name_or any string data which you want to post"]
let data : Data = user1.data(using: .utf8)!
//create the session object
let session = URLSession.shared
//now create the Request object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to data object and set it as request body
} catch let error {
print(error.localizedDescription)
completion(nil, error)
}
//HTTP Headers
request.setValue("Bearer \(ttkknn)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.setValue(NSLocalizedString("lang", comment: ""), forHTTPHeaderField:"Accept-Language");
request.httpBody = data
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request, completionHandler: { data, response, error in
guard error == nil else {
completion(nil, error)
return
}
guard let data = data else {
completion(nil, NSError(domain: "dataNilError", code: -100001, userInfo: nil))
return
}
do {
//create json object from data
guard let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] else {
completion(nil, NSError(domain: "invalidJSONTypeError", code: -100009, userInfo: nil))
return
}
print(json)
} catch let error {
print(error.localizedDescription)
completion(nil, error)
}
})
task.resume()
}
推荐阅读
- apache - Tomcat 服务器上的 HTTP 洪水导致问题
- spring - 在每次测试之前触发 Flyway 迁移
- github-actions - GitHub Actions:如何在容器中运行作业
- javascript - 无法使用条件渲染渲染不同的结果
- three.js - 如何知道 react-three-fiber 中“Canvas”的所有属性?
- dataframe - Spark 数据集过滤器元素
- javascript - React material-ui 工具提示悬停(当项目被禁用时触发事件触发器)
- python - 过滤出预设日期和时间的数据框
- google-cloud-platform - 如何在 GCP 中为未知的自定义指标创建警报策略
- cucumber - 黄瓜小黄瓜在同一场景中使用不同的数据文件