POST with swift and API

后端 未结 3 1879
孤街浪徒
孤街浪徒 2020-12-09 07:05

I\'ve a problem when I try to send a POST request to my API on my server, I\'ve followed many many different tutorials but it still doesn\'t work. I know than my problem is

3条回答
  •  醉酒成梦
    2020-12-09 07:12

    the following php code is for receiving application/url+encode encoded post message. please refer https://en.wikipedia.org/wiki/Percent-encoding

    $_POST["pseudo"]
    

    and your swift code was sending a JSON encoded string data. They are incompatible.

    If you don't want to change the php code, in Swift you should send url-encode format message, li:

    // UPDATED with corrections from @Rob

        var params = ["param1":"value1", "papam2": "value 2"]
        var body = ""
        for (key, value) in params {
            body = body.stringByAppendingString(key)
            body = body.stringByAppendingString("=")
            body = body.stringByAppendingString(value.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
            body = body.stringByAppendingString("&")
        }
        body = body.substringToIndex(advance(body.startIndex, countElements(body)-1)) // remove the last "&"
        request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
    

提交回复
热议问题