IOS网址请求问题

时间:2018-02-13 17:25:11

标签: ios swift xcode

我想将手机号码和密码发送到ios应用中的服务器。后端团队给出了邮政编码API,如下图所示。

以表单数据形式发送时成功

enter image description here

Swift网址请求失败,我在这里做错了什么?

  func sendReq() {
    let Url                 = String(format: "http://xxxxxxx/mobile/request_otp")
    guard let serviceUrl    = URL(string: Url) else { return }
    let parameterDictionary = ["mobile_number" : "xxxxxxxxxx", "password" : "12345678"]
    var request             = URLRequest(url: serviceUrl)
    request.httpMethod      = "POST"
    request.cachePolicy     = .useProtocolCachePolicy
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    //  params dict as data
    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameterDictionary, options: []) else {
        return
    }
    request.httpBody        = httpBody

    // session
    let session             = URLSession.shared

    //data task
    session.dataTask(with: request) { (data, response, error) in
        if let response = response {
            print(response)
        }
        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
            }
            catch {
                print(error)
            }
        }
        }.resume()
}

但是上面的API调用抛出错误,如

{
    error = TRUE;
    message = "All fields Required!";
}

2 个答案:

答案 0 :(得分:0)

你可以尝试:

{\"mobile_number\":xxxxxxxxxx,\"password\":12345678}

并选择Application / Json而不是text。

答案 1 :(得分:0)

设置Content-Type HTTP标头:

request.allHTTPHeaderFields = ["Content-Type": "application/json"]

这样您就可以通知服务器您正在发送JSON。