mehmeet43
mehmeet43

Reputation: 183

Error: when post on Swift

I’ve got below post service from backend developer and now I’m trying to implement it on swift.

<form role="form" method="post" action=“order_post.asp" id="frmBack">
    <input type="hidden" name="product_id" value="297">
    <input type="hidden" name="order_no" value="010223005373"> 
    <input type="hidden" name=“city” value=“Paris”>
    <input type="hidden" name=“county” value=“La Fayette”>
    <input type="hidden" name="price" value="143">
    <input type="hidden" name=“receiver_name” value=“Jane Doe”>
    <input type="hidden" name=“sender_name” value=“John Doe“>
    <input type="submit" id="submit_back_handle">

I have wrote below code but it didn’t work and ask me to fill all fields on the form. Can anybody tell me what I’m missing?

 func post() {

    let params = [
        “product_id": "297",
        “order_no": "010215135311",
        “city”: “Paris”,
        “county”: “La Fayette“,
        "price": "143",
        "receiver_name": “Jane Doe“,
        "sender_name": “John Doe”,
        ] as Dictionary <String, String>

    let request = NSMutableURLRequest(URL: NSURL(string: "http://webservis.mydomain.com/order_post.asp")!)

    let session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])

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


        guard data != nil else {
            print("no data found: \(error)")
            return
        }

        do {
            if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                let success = json["success"] as? Int                                  // Okay, the `json` is here, let's get the value for 'success' out of it
                print("Success: \(success)")
            } else {

                let cfEnc = CFStringEncodings.ISOLatin5
                let enc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEnc.rawValue))

                let jsonStr = NSString(data: data!, encoding: enc)    // No error thrown, but not NSDictionary
                print("Error could not parse JSON: \(jsonStr)")
            }
        } catch let parseError {
            print(parseError)                                                          // Log the error thrown by `JSONObjectWithData`

            let cfEnc = CFStringEncodings.ISOLatin5
            let enc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEnc.rawValue))

            let jsonStr = NSString(data: data!, encoding: enc)
            print("Error could not parse JSON: '\(jsonStr)'")
        }
    }

    task.resume()

}

And response and request headers below when I sniff the web site;

Response Headers

Cache-Control:private
Content-Encoding:gzip
Content-Length:6876
Content-Type:text/html
Date:Sat, 02 Jan 2016 16:11:30 GMT
Server:Microsoft-IIS/8.5
Set-Cookie:xxx; secure; path=/
Vary:Accept-Encoding
X-Powered-By:ASP.NET
X-Powered-By-Plesk:PleskWin

Request Headers

 Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
 Accept-Encoding:gzip, deflate
 Accept-Language:en-US,en;q=0.8
 Cache-Control:max-age=0
 Connection:keep-alive
 Content-Length:526
 Content-Type:application/x-www-form-urlencoded
 Cookie:xxx
 Host:xxx
 Origin:xxx
 Referer:xxx
 Upgrade-Insecure-Requests:1
 User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) >      AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36

Upvotes: 0

Views: 76

Answers (1)

mehmeet43
mehmeet43

Reputation: 183

My code start to work after I changed dictionary with below jsonString and request.HTTPBody method regarding jsonString.

let form1 = "product_id=297&order_no=010215135311&city=Paris&…”

request.HTTPBody = form1.dataUsingEncoding(NSUTF8StringEncoding)

I suppose it was encoding problem but I'm not sure.

Upvotes: 1

Related Questions