Search code examples
swifthttprequest

How to translate a python script to swift (http post request)?


I have a working python script that gets cookies from a site. I want to convert it to Swift script, but I do something wrong and can not understand where.

#!/usr/bin/env python
import warnings
import json
import os
import requests

auth_login='someName'
auth_password='somePassword'
passport_params = {'from': 'passport', 'retpath': 'https://192.168.0.1/passport?mode=passport', 'passwd': auth_password, 'login': auth_login, 'display': 'page'}
passport_session = requests.session()
passport_error_passwd = u"wrong pass"
passport_error_login = u"no such users"
print('Connecting to passport...')
try:
    passport_request = passport_session.post('https://192.168.0.1/passport?mode=auth', data=passport_params, verify=False)
except:
    print('Error connecting')
if os.name == 'nt':
    os.system("pause")
    exit(1)
else:
    print('Authentication successful')
    passport_cookies = requests.utils.dict_from_cookiejar(passport_session.cookies)
    print('cookies=')
    print(passport_cookies)

I am not sure that my post request works correctly, so my cookies are empty.

let auth_login = "someName"
let auth_password = "somePassword"
let url = URL(string: "https://192.168.0.1/passport?mode=auth")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.httpMethod = "POST"

let parameters = [
    "from": "passport",
    "retpath": "https://192.168.0.1/passport?mode=passport",
    "passwd": auth_password,
    "login": auth_login,
    "display": "page"
]

request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard
//        let data = data,
        let response = response as? HTTPURLResponse,
        let fields = response.allHeaderFields as? [String: String]
    else {
        print("error", error ?? URLError(.badServerResponse))
        return
    }

    let cookies = HTTPCookie.cookies(withResponseHeaderFields: fields, for: url)
    print("cookies:\n\(cookies)")

    
    guard (200 ... 299) ~= response.statusCode else {                  
        print("statusCode should be 2xx, but is \(response.statusCode)")
        print("response = \(response)")
        return
    }
        
}

task.resume()


Solution

  • Your python code is sending these:

    passport_params = {'from': 'passport', 'retpath': 'https://192.168.0.1/passport?mode=passport', 'passwd': auth_password, 'login': auth_login, 'display': 'page'}
    

    as POST data payload.

    While your Swift code

    let parameters = [
        "from": "passport",
        "retpath": "https://192.168.0.1/passport?mode=passport",
        "passwd": auth_password,
        "login": auth_login,
        "display": "page"
    ]
    
    request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)
    

    is doing that as JSON http body.

    So these requests are very different, hence the problem you encounter.

    Have a look at this answer how to configure POST data in a request in Swift .