Why the http post request body always wrapped by Optional text in the Swift app

删除回忆录丶 提交于 2019-12-12 05:12:45

问题


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")

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!


回答1:


I found the problem!

The correct content type declaration;

request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")    

The wrong content type declaration;

request.setValue("application/json", forHTTPHeaderField: "Content-Type")    

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!

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!




回答2:


Just change your variable and add an '!' to your variable. That way, it isn't an optional anymore and you don't have that kind of problem.

var postString: String! = "id=john&password=1111"


来源:https://stackoverflow.com/questions/28149368/why-the-http-post-request-body-always-wrapped-by-optional-text-in-the-swift-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!