问题描述
我正在编写 swift 代码以向 php 服务器发送 http post 请求.但是我的php脚本总是得到奇怪的帖子正文,因为参数被Option()包裹,如果我发送像id=john&password=1234"这样的参数,服务器将得到Optional(id=john&password=1234).但这不是我想要的,因为php无法以正常方式分析参数.我不知道这里出了什么问题;
I am writing the swift code to send a http post request to the php server. But my php script always get the strange post body because the parameters are wrapped by the Option(), If I send parameters like "id=john&password=1234", the server will get Optional(id=john&password=1234). But this is not what I want because php cannot analyse the parameters in the normal way. I have no idea about what's going wrong here;
var postString: String = "id=john&password=1111"
request.HTTPBody = (postString.dataUsingEncoding(NSUTF8StringEncoding))
println("Body will send: \(request.HTTPBody)")
var postLength:NSString = String( postString2.dataUsingEncoding(NSUTF8StringEncoding)!.length )
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("multipart/form-data", forHTTPHeaderField: "Accept")
经过上面的准备代码,我使用dataTaskWithRequest方法发送帖子.在谷歌这个问题几天后,我对这个未解决的问题感到疯狂.需要一个线索来修复它.请指教!
After the above preparing code, I use dataTaskWithRequest method to send the post. After google this question for several days, I am going crazy about this unsolved problem. Need a clue to fix it. Please advise!
推荐答案
我发现了问题!
正确的内容类型声明;
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
错误的内容类型声明;
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
非常感谢您的建议和提示提醒!终于明白问题不在 Optional 包裹的 String 里面,而是在其他 http 属性里面!
Thanks a lot for the advice and hint reminder! Finally I understand the problem is not inside the Optional wrapped String but the other http properties!
昨天我使用 php 将请求正文回显到客户端进行调试,并且我总是将 String 包裹在 Optional 中,这很愚蠢!看完这些评论后,我要求php程序员将每个请求体记录到本地文件并检查内容......................没有可选的包装字符串.
Yesterday I use php to echo the request body to the client for the debug and I always got the String wrapped with Optional, this is stupid! After read these comments, I ask php programmer to log each request body to the local file and check the content................. there is no Optional wrapped string.
对不起,代码很愚蠢,非常感谢您的帮助!你们真棒!
Sorry for the stupid code and thanks a lot for your help! You guys are awesome!
这篇关于为什么 Swift 应用程序中的 http post 请求正文总是由 Optional 文本包裹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!