简体   繁体   中英

How do I can add POST params in URLSession request in Swift

I wanna add POST params into my URLSession request to my server. Server code:

if (isPost()) {
$response["code"] = 200;
$response["message"] = "success";

if (isset($_POST['imei']) && isset($_POST['token'])) {
    $db = getDB();

    $imei = $_POST['imei'];
    $token = $_POST['token'];

    $token = getTokenFromServer($db, $imei);
    //echo $token;

}else {
    $response["code"] = 400;
    $response["message"] = "no params sent";
}

}else {
    $response["code"] = 400;
    $response["message"] = "is not post method";
}

And here is client code in Swift :

guard let url = URL(string: "https://api-ru.000webhostapp.com/auth.php") else { return }

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("text", forHTTPHeaderField: "hello")
    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in

        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
            } catch {
                print("ERROR")
                print(error)
            }
        }

        }.resume()

I always get

{
   code = 400;
   message = "no params sent";
}

I tried to add following code

request.addValue("345346343", forHTTPHeaderField: "imei")
request.addValue("sdfsdHsdlf43sdfFGsd3l", forHTTPHeaderField: "token")

But it din't help me. Help me please how do I can add params to get 200 . Thanks.

you can send them with request.httpBody

Like that :

guard let url = URL(string: "https://api-ru.000webhostapp.com/auth.php") else { return }

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
  //  request.addValue("text", forHTTPHeaderField: "hello")
  request.addValue("application/json", forHTTPHeaderField: "Content-Type")
   request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Accept")

   let parameters = ["imei": "imeiValue", "token": "tokenValue"]
do {
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)  // Json Body
    } catch let error {
        print(error.localizedDescription)
    }

    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in

        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
            } catch {
                print("ERROR")
                print(error)
            }
        }

        }.resume()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM