【问题标题】:iOS Swift POST api with x-www-form-urlencoded带有 x-www-form-urlencoded 的 iOS Swift POST api
【发布时间】:2018-06-29 11:16:03
【问题描述】:

我必须进行 API 调用,其中标头为“application/x-www-form-urlencoded”,正文中的“数据”为键,vakue 为 JSON 字符串。我必须以 application/x-www-form-urlencoded 格式传递数据。我附上了邮递员的截图,它工作正常。

[带有标头的图像][带有帖子数据的图像作为 x-www-form-urlencoded 标记]

我尝试了很多链接,例如POST request using application/x-www-form-urlencoded。但是找不到正确的。

我可以使用 Alamofire 等其他框架来解决这个问题。

我为此使用以下代码。

    let url = URL(string: "http://mylocalhost/get-user-details")!
    var request = URLRequest(url: url)
    let jsonString = ["email":"example@domain.com"]
    let postData = ["data":jsonString]
    let jsonData = try! JSONSerialization.data(withJSONObject: postData, options: .prettyPrinted)

    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    request.httpBody = jsonData

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(error)")
            return
        }

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

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

    task.resume()

【问题讨论】:

  • JSONSerialization.data(withJSONObject: postData, options: .prettyPrinted)。不要使用prettyPrinted,这会添加无用的换行符。请改用JSONSerialization.data(withJSONObject: postData, options: [])。另外,我想知道您是否在 JSON 中没有婴儿 JSON。意思是jsonString 必须是"{\"email\":\"example@domain.com\"},因为很明显,当它是字典时,将变量命名为jsonString,这是一种误导,但邮递员可以这么说。
  • 为什么不简单地在“Content-Type”中使用“application/json”。

标签: ios swift


【解决方案1】:

如果您想使用 Alamofire,请使用此方法。

 func request(_ method: HTTPMethod
    , _ URLString: String
    , parameters: [String : AnyObject]? = [:]
    , headers: [String : String]? = [:]
    , onView: UIView?, vc: UIViewController, completion:@escaping (Any?) -> Void
    , failure: @escaping (Error?) -> Void) {

    Alamofire.request(URLString, method: method, parameters: parameters, encoding: URLEncoding.default, headers: headers)
        .responseJSON { response in


            switch response.result {
            case .success:
                completion(response.result.value!)
            case .failure(let error):
                failure(error)
                guard error.localizedDescription == JSON_COULDNOT_SERIALISED else {

                    return
                }
            }
    }
}

在头参数中传递这个

["Content-Type": "application/x-www-form-urlencoded"]

【讨论】:

    【解决方案2】:

    这对我有用,用这个替换你的第 6 行:

    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-21
      • 2021-01-24
      • 2014-03-30
      • 1970-01-01
      相关资源
      最近更新 更多