Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

swift3 - How to send form data in POST request in Swift 3

I am trying to post form-data using webservice, userName & password, but in response it's showing an error stating "Could not connect to the server.".

Please help me to send form data in the POST request.

        let dict:[String:String] = ["userName": userName as! String, "password": password as! String]

        do {

            let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)

            let url = URL(string: "(some url)")!

            var request  = URLRequest(url: url)

            request.httpMethod = "POST"

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

            request.httpBody = jsonData

            let task = URLSession.shared.dataTask(with: request) { data, response, error in

                if error != nil {

                    print(error!.localizedDescription)

                    return

                }

                do {

                    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                    if let parseJSON = json {

                        let resultValue:String = parseJSON["success"] as! String;

                        print("result: (resultValue)")

                        print(parseJSON)

                    }

                } catch let error as NSError {

                    print(error)

                }
            }

            task.resume()

        } catch {

            print(error.localizedDescription)

        }

I've tried adding values in the request, may be some values are missing in the request formed. Please help!

Thats the POSTMAN response

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

my calling api class

class ApiService
{
    static func getPostString(params:[String:Any]) -> String
    {
        var data = [String]()
        for(key, value) in params
        {
            data.append(key + "=(value)")
        }
        return data.map { String($0) }.joined(separator: "&")
    }

    static func callPost(url:URL, params:[String:Any], finish: @escaping ((message:String, data:Data?)) -> Void)
    {
        var request = URLRequest(url: url)
        request.httpMethod = "POST"

        let postString = self.getPostString(params: params)
        request.httpBody = postString.data(using: .utf8)

        var result:(message:String, data:Data?) = (message: "Fail", data: nil)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in

            if(error != nil)
            {
                result.message = "Fail Error not null : (error.debugDescription)"
            }
            else
            {
                result.message = "Success"
                result.data = data
            }

            finish(result)
        }
        task.resume()
    }
}

and when use it

ApiService.callPost(url: url, params: params, finish: finishPost)

and the finish function

func finishPost (message:String, data:Data?) -> Void
{
    do
    {
        if let jsonData = data
        {
            let parsedData = try JSONDecoder().decode(Response.self, from: jsonData)
            print(parsedData)
        }
    }
    catch
    {
        print("Parse Error: (error)")
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...