将Json与发布请求绑定 [英] bind Json with post request

查看:136
本文介绍了将Json与发布请求绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过一整天的尝试并检查了堆栈溢出和许多论坛上的许多链接后,我无法破解:我认为许多swift开发人员都觉得很简单,但我无法破解,请帮忙

我有一个URL和一个JSON来绑定并获取JSON响应

发送到POST的网址: http://myurl/myurl.com ... ....//

JSON请求:

{
"BookingId": "1501433021",
"ProductType": "0",
"Client": "1",
"OriginAirport": {
    "CityCode": "NYC",
    "CityName": "New York",
    "AirportCode": "NYC",
    "AirportName": "New York City All Airports",
    "Country": "US",
    "Terminal": ""
},
"DestinationAirport": {
    "CityCode": "LON",
    "CityName": "London",
    "AirportCode": "LON",
    "AirportName": "London All Airports",
    "Country": "GB",
    "Terminal": ""
},
"TravelDate": "2016-10-19T05:07:57.865-0400 ",
"ReturnDate": "2016-10-21T05:08:02.832-0400 ",
"SearchDirectFlight": false,
"FlexibleSearch": false,
"TripType": 2,
"Adults": 1,
"Children": 0,
"Infants": 0,
"CabinType": 1,
"SearchReturnFlight": true,
"Airline": "",
"CurrencyCode": "USD",
"SiteId": "LookupFare"
}

MyCode(此代码是从一些我只是想使其对我有用的地方复制的),显然对我不起作用

import UIKit

class SearchFlightsVC: UIViewController{

    override func viewDidLoad() {

        print("vdfvdfvdf")

        // prepare json data
        let json = ["BookingId": "1501433021",
                                    "ProductType": "0",
                                   "Client": "1",
                                    "OriginAirport": [
                                        "CityCode": "CLT",
                                        "CityName": "Charlotte",
                                        "AirportCode": "CLT",
                                        "AirportName": "Douglas Intl",
                                        "Country": "US",
                                        "Terminal": ""
                                    ],
                                    "DestinationAirport": [
                                        "CityCode": "YTO",
                                        "CityName": "Toronto",
                                        "AirportCode": "YTO",
                                        "AirportName": "Toronto All Airports",
                                        "Country": "CA",
                                        "Terminal": ""
                                    ],
                                    "TravelDate": "2016-10-19T05:07:57.865-0400",
                                    "ReturnDate": "2016-10-21T05:08:02.832-0400",
                                    "SearchDirectFlight": false,
                                    "FlexibleSearch": false,
                                    "TripType": 2,
                                    "Adults": 1,
                                    "Children": 0,
                                    "Infants": 0,
                                    "CabinType": 1,
                                    "SearchReturnFlight": true,
                                    "Airline": "",
                                    "CurrencyCode": "USD",
                                    "SiteId": "LookupFare" ]

        do {

            let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)
            print(jsonData)


            // create post request
            let url = NSURL(string: "http://myurl/myurl.com.......//")!
            let request = NSMutableURLRequest(URL: url)
            request.HTTPMethod = "POST"

            // insert json data to the request
            request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
            request.HTTPBody = jsonData


            let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in

                print(response)


                if error != nil{
                    print("Error -> \(error)")
                    return
                }

                do {
                    let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]

                    print("Result -> \(result)")

                } catch {
                    print("Error -> \(error)")
                }
            }

            //task.resume()
            //return task



        } catch {
            print(error)
        }
}
}

我已经检查了

如何创建并使用快速语言将json数据发送到服务器

使用POST方法的Swift HTTP请求

但是对我没有任何作用

感谢所有帮助,谢谢!!!

解决方案

这是我为我的应用编写的代码,并根据您的要求进行了自定义

         func sendRequest(address: String, method: String, body: Dictionary<String, AnyObject>) {
        let url = NSURL(string: address)
        let request = NSMutableURLRequest(URL: url!)
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.HTTPMethod = method

        do {
            request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(body, options: NSJSONWritingOptions.init(rawValue: 2))
        } catch {
            // Error handling
            print("There was an error while Serializing the body object")
            return
        }

        let session = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in

            do {
                if error != nil {
                    print("Error -> \(error)")
                    return
                }

                if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? [NSDictionary] {
                    let result = json
                }

            } catch {
                print("Send request error while Serializing the data object")
                return
            }

        })

        session.resume()

    }

    sendRequest("your.URL.come", method: "POST", body: json)

希望这会有所帮助,还有一件事是将TransportSecurity添加到您的info.plist或复制行打击并用您的基本地址更改"your.URL.come"

  <key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>your.URL.come</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

希望这会有所帮助

After trying from a whole day and checking many links on stack overflow and few forums I am not able to crack it : I think many swift developers finds it very easy but I am not able to crack it please help

I Have a url and a JSON to bind and get the JSON Response

Url to POST: http://myurl/myurl.com.......//

JSON Request:

{
"BookingId": "1501433021",
"ProductType": "0",
"Client": "1",
"OriginAirport": {
    "CityCode": "NYC",
    "CityName": "New York",
    "AirportCode": "NYC",
    "AirportName": "New York City All Airports",
    "Country": "US",
    "Terminal": ""
},
"DestinationAirport": {
    "CityCode": "LON",
    "CityName": "London",
    "AirportCode": "LON",
    "AirportName": "London All Airports",
    "Country": "GB",
    "Terminal": ""
},
"TravelDate": "2016-10-19T05:07:57.865-0400 ",
"ReturnDate": "2016-10-21T05:08:02.832-0400 ",
"SearchDirectFlight": false,
"FlexibleSearch": false,
"TripType": 2,
"Adults": 1,
"Children": 0,
"Infants": 0,
"CabinType": 1,
"SearchReturnFlight": true,
"Airline": "",
"CurrencyCode": "USD",
"SiteId": "LookupFare"
}

MyCode (this code is copied from some where I am just trying to make it work for me) Which obviously not working for me

import UIKit

class SearchFlightsVC: UIViewController{

    override func viewDidLoad() {

        print("vdfvdfvdf")

        // prepare json data
        let json = ["BookingId": "1501433021",
                                    "ProductType": "0",
                                   "Client": "1",
                                    "OriginAirport": [
                                        "CityCode": "CLT",
                                        "CityName": "Charlotte",
                                        "AirportCode": "CLT",
                                        "AirportName": "Douglas Intl",
                                        "Country": "US",
                                        "Terminal": ""
                                    ],
                                    "DestinationAirport": [
                                        "CityCode": "YTO",
                                        "CityName": "Toronto",
                                        "AirportCode": "YTO",
                                        "AirportName": "Toronto All Airports",
                                        "Country": "CA",
                                        "Terminal": ""
                                    ],
                                    "TravelDate": "2016-10-19T05:07:57.865-0400",
                                    "ReturnDate": "2016-10-21T05:08:02.832-0400",
                                    "SearchDirectFlight": false,
                                    "FlexibleSearch": false,
                                    "TripType": 2,
                                    "Adults": 1,
                                    "Children": 0,
                                    "Infants": 0,
                                    "CabinType": 1,
                                    "SearchReturnFlight": true,
                                    "Airline": "",
                                    "CurrencyCode": "USD",
                                    "SiteId": "LookupFare" ]

        do {

            let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)
            print(jsonData)


            // create post request
            let url = NSURL(string: "http://myurl/myurl.com.......//")!
            let request = NSMutableURLRequest(URL: url)
            request.HTTPMethod = "POST"

            // insert json data to the request
            request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
            request.HTTPBody = jsonData


            let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in

                print(response)


                if error != nil{
                    print("Error -> \(error)")
                    return
                }

                do {
                    let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]

                    print("Result -> \(result)")

                } catch {
                    print("Error -> \(error)")
                }
            }

            //task.resume()
            //return task



        } catch {
            print(error)
        }
}
}

I already checked

How to create and send the json data to server using swift language

HTTP Request in Swift with POST method

But nothing works for me

ALL HELP IS Appreciated Thanks in Advance !!!

解决方案

This is the code I wrote for my app and customized for your request

         func sendRequest(address: String, method: String, body: Dictionary<String, AnyObject>) {
        let url = NSURL(string: address)
        let request = NSMutableURLRequest(URL: url!)
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.HTTPMethod = method

        do {
            request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(body, options: NSJSONWritingOptions.init(rawValue: 2))
        } catch {
            // Error handling
            print("There was an error while Serializing the body object")
            return
        }

        let session = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in

            do {
                if error != nil {
                    print("Error -> \(error)")
                    return
                }

                if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? [NSDictionary] {
                    let result = json
                }

            } catch {
                print("Send request error while Serializing the data object")
                return
            }

        })

        session.resume()

    }

    sendRequest("your.URL.come", method: "POST", body: json)

hope this will help to and one more thing add TransportSecurity to your info.plist or copy line blow and change the "your.URL.come" with your base address

  <key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>your.URL.come</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

hope this will help

这篇关于将Json与发布请求绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆