-->

Why the http post request body always wrapped by O

2019-09-03 20:17发布

问题:

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"