0
votes

I'm trying to send a POST request in my app. But server response 400. I tried to use solutions from string varient and json varient. Both cases I'm getting error code 400, but if I send same request via postman it response 200, and works properly. Server API using "http" and I set plist properties for it.

func requestSmsCode() {

    let postUrl = URL(string: "http://www.myServer.com/auth/send_phone")

    var request = URLRequest(url: postUrl!)
    request.httpMethod = "POST"
    let postString = "phone=myPhone"
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }

        let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(responseString)")
    }
    task.resume()
}


func requestSmsCodeWithJSON() {


    let json: [String: Any] = ["phone": "myPhone"]

    let jsonData = try? JSONSerialization.data(withJSONObject: json)

    let url = URL(string: "http://www.myServer.com/auth/send_phone")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    request.httpBody = jsonData

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print(error?.localizedDescription ?? "No data")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }

        let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
        if let responseJSON = responseJSON as? [String: Any] {
            print(responseJSON)
        }
    }

    task.resume()
}
1
What does the server side code look like?kichik
@kichik Unfortunately, its black box for me. Should be some problem in there? requset via postman works fine somehowsedq
Well, it'd be much easier to know what's wrong with this code if we know what the server expects. If Postman works, it'd help to see the exact request it sends.kichik

1 Answers

1
votes

I recommend you use a debugging proxy service like https://www.charlesproxy.com/ to see how the request is being made. Then you can make the request with postman again and compare them to find exacly where they differ.