gpt4 book ai didi

ios - swift post请求编码加号变为空白

转载 作者:搜寻专家 更新时间:2023-10-31 08:22:47 25 4
gpt4 key购买 nike

最近我发现当我发送包含“+”号的post数据时,“+”会变成空白。例如 { dish_name: fish+chips }。这导致服务器端无法读取数据。所以我尝试跟随,我使用:

request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

将我的请求编码为 UTF-8。但是,这一行导致我的发布数据变为空。我不知道为什么会这样。 或者有没有更好的解决方案来在发布方法中将“+”号保持为本身?

func PostMethod(url:NSURL,Data:String) {

let request = NSMutableURLRequest(URL: url)
let session = NSURLSession.sharedSession()
let submitContent = Data
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
request.HTTPBody = submitContent.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)


//print("——request——")
//print(request)

let task = session.dataTaskWithRequest(request){
data, response, error in


if data != nil{

let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
print(responseString)

let jsonall = self.commonControl.StringToJson(responseString)
if let dataFromString = jsonall["body"].stringValue.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
let json = JSON(data: dataFromString)
}}}}

最佳答案

您可以尝试将您的 + 转换成它的 ASCII 码。例如:

让 content = exampleString.stringByReplacingOccurrencesOfString("+", withString: "%2B", options: [], range: nil)

swift 3+

let content = exampleString.replacingOccurrences(of: "+", with: "%2B")

关于ios - swift post请求编码加号变为空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36854981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com