首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swift-4 :如何使用带有“Content”:“application/x form-urlencoded”的URLSession中的参数的POST请求获取数据

Swift-4 :如何使用带有“Content”:“application/x form-urlencoded”的URLSession中的参数的POST请求获取数据
EN

Stack Overflow用户
提问于 2018-11-20 07:48:21
回答 2查看 4.9K关注 0票数 1

朋友们,我已经看过了很多关于S.O的例子,虽然我还没有得到正确的答案,但是我仍然面临着使用带有Post请求的URLSession获取数据的问题&并使用它传递参数。

首先,我想向你展示我拥有的一切。到现在为止..。

代码语言:javascript
复制
func requestApiCall(){

    let renewal_id = ""
    let policy_no = ""
    let client_name = ""
    let client_id = ""
    let product_name = ""
    let created_date_from = ""
    let created_date_to = ""
    let policy_expiry_from = ""
    let policy_expiry_to = ""

    self.parameters = ["renewal_id":renewal_id,"policy_no":policy_no,"client_name":client_name,"client_id":client_id,"product_name":product_name,"created_date_from":created_date_from,"created_date_to":created_date_to,"policy_expiry_from":policy_expiry_from,"policy_expiry_to":policy_expiry_to]

    let config = URLSessionConfiguration.default
    config.httpAdditionalHeaders = [
        "Accept" : "application/json",
        "Content-Type" : "application/x-www-form-urlencoded"
    ]
    let session = URLSession(configuration: config)
    let Url = String(format: "http://myapi-url");
    let serviceUrl = URL(string: Url)
    var request = URLRequest(url: serviceUrl!)
    print(request.url!)
    request.httpMethod = "POST"
    request.timeoutInterval = 60

    request.httpBody  = try! JSONSerialization.data(withJSONObject: parameters!, options: [])

    let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in

        if error == nil{
            print(response!)
        }
        else {
            print(error?.localizedDescription as Any)
        }

        print(response!)
        guard let httpResponse = response as? HTTPURLResponse, let receivedData = data
            else {
                print("error: not a valid http response")
                return
        }

        switch (httpResponse.statusCode)
        {
        case 200: //The request was fulfilled
            let response = NSString (data: receivedData, encoding: String.Encoding.utf8.rawValue)

            if response == "SUCCESS"
            {
                print("Network - HandShaking Successfull...!!!")
            }
            else{
                print("Network - HandShaking is not successfull...!!!")
            }

        case 400:
            print("response-status - 400 : The request had bad syntax or was inherently impossible to be satisfied.")
        case 500:
            print("\nresponse-status - 500 : Internal Server Error...!!!")
        default:
            print("response-status - Unknown : Received Response =>  \(httpResponse.statusCode)")
        }
    })
    task.resume()
}

在运行上述函数之后,我得到了httpResponse.statusCode = 500

但是当我在邮递员里运行这个时,我得到了适当的回应,就像我的天赋。

邮递员申请

此外,我还试图通过postman...which生成代码片段,如下所示.

代码语言:javascript
复制
func postmanSnippetApiCall(){
    let headers = [
        "Content-Type": "application/x-www-form-urlencoded",
        "cache-control": "no-cache",
        "Postman-Token": "5d571157-86c5-4eac-ba6d-b00779ae5dbd"
    ]

    let postData = NSMutableData(data: "renewal_id=".data(using: String.Encoding.utf8)!)
    postData.append("&policy_no=".data(using: String.Encoding.utf8)!)
    postData.append("&client_name=".data(using: String.Encoding.utf8)!)
    postData.append("&client_id=".data(using: String.Encoding.utf8)!)
    postData.append("&product_name=".data(using: String.Encoding.utf8)!)
    postData.append("&created_date_from=".data(using: String.Encoding.utf8)!)
    postData.append("&created_date_to=".data(using: String.Encoding.utf8)!)
    postData.append("&policy_expiry_from=".data(using: String.Encoding.utf8)!)
    postData.append("&policy_expiry_to=".data(using: String.Encoding.utf8)!)
    postData.append("&undefined=undefined".data(using: String.Encoding.utf8)!)

    let request = NSMutableURLRequest(url: NSURL(string: "http://myapiurl")! as URL,
                                      cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)
    request.httpMethod = "POST"
    request.allHTTPHeaderFields = headers
    request.httpBody = postData as Data

    let session = URLSession.shared
    let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
        if (error != nil) {
            print(error)
        } else {
            let httpResponse = response as? HTTPURLResponse
            print(httpResponse)
        }
    })

    dataTask.resume()
}

但是在postman生成的代码片段中,我在这一行中接收到错误,即request.httpBody = postData as Data error 是这样的:Cannot convert value of type 'NSMutableData' to type 'Data' in coercion

如果我使用thirdParty库,即Alamofire,那么我可以非常容易地获得数据。

Alamofire代码snippet...runs ..&给出了正确的响应.

代码语言:javascript
复制
func apiRequestByAlamofire(){
        let urlString = "http://myapiurl"

        let params: [String: Any]? = ["renewal_id":"","policy_no":"","client_name":"","client_id":"","product_name":"","created_date_from":"","created_date_to":"","policy_expiry_from":"","policy_expiry_to":""]

        Alamofire.request(urlString, method: .post, parameters: params).responseJSON { response in
            print(response) //Here getting perfect response successfully...!!!
        }

    }

,但我还是在通过URLSession.!来解决这个问题

我仍然怀疑,这就是为什么我在使用URLSession时遇到太多问题的原因。

朋友们,毫无疑问,请允许我接受你们的建议,也请帮助我理解它。

不知道,我哪里搞错了。请帮帮我。

EN

回答 2

Stack Overflow用户

发布于 2018-11-20 10:18:27

我给你简单的功能,你可以根据你的要求编辑这个功能。您也可以更改您的URL和params。在响应中,我编写了两行(如果从服务器获取JSON数组),然后使用第一个(如果使用对象),然后使用第二个(另一个)删除这两行。

代码语言:javascript
复制
func abc()  {
    let request = NSMutableURLRequest(url: URL(string: "Your URL")!)
    request.httpMethod = "POST"
    let postString = "param_name_one=\( value_1 )&param_name_two=\(value_2)&........."
    request.httpBody = postString.data(using: String.Encoding.utf8)
    let task = URLSession.shared.dataTask(with: request as URLRequest) {
        data, response, error in
        if(error != nil){
            // Show Error Message
        } else{
            do {
                //For JSON ARRAY
                let jsonItem  = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSArray
                let json = jsonItem[0] as AnyObject
               //For JSON object 
                let json_object  = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as AnyObject
                print(json_object)
                
            } catch {
                
            }
        }
    }
    task.resume();
}
票数 0
EN

Stack Overflow用户

发布于 2020-07-21 15:12:39

经过大量的探索和斗争,我想出了一个解决方案:

代码语言:javascript
复制
        guard var components = URLComponents(url: URL(string: "http://example.com")!, resolvingAgainstBaseURL: true)
            else { fatalError("Couldn't create URLComponents") }
        
        components.queryItems = params.map { k, v in URLQueryItem(name: k, value: v) }
        
        var request = URLRequest(url: baseUrl.appendingPathComponent(path.rawValue))
        request.httpBody = Data(components.query!.utf8)
        request.httpMethod = "POST"

"example.com“可以是字面意思,因为我只是使用URLComponents对参数进行编码。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53388406

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档