带有x-www-form-urlencoded的iOS Swift POST API

时间:2018-06-29 11:16:03

标签: ios swift

我必须使用标头作为“ application / x-www-form-urlencoded”的API调用,并在主体“ data”中将其作为键,并将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()

3 个答案:

答案 0 :(得分: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"]

答案 1 :(得分:0)

尝试一下

var request = URLRequest(url: URL(string: strURL)!)
    request.httpMethod = "POST"
    let params = ["email":"example@domain.com"]
    let postString = params
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        DispatchQueue.main.async {
            guard let data = data, error == nil else {
                print(error! as NSError)
                return
            }
            do {
                let jsonDic = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:AnyObject]
                success(jsonDic! as NSDictionary)
            } catch {
                print(error as NSError)
            }
        }
    }
    task.resume()

答案 2 :(得分:0)

这对我有用,将您的第六行替换为:

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