HTTP Request in Swift with POST method

前端 未结 7 907
名媛妹妹
名媛妹妹 2020-11-22 05:46

I\'m trying to run a HTTP Request in Swift, to POST 2 parameters to a URL.

Example:

Link: www.thisismylink.com/postName.php

Params:

7条回答
  •  一向
    一向 (楼主)
    2020-11-22 06:29

    For anyone looking for a clean way to encode a POST request in Swift 5.

    You don’t need to deal with manually adding percent encoding. Use URLComponents to create a GET request URL. Then use query property of that URL to get properly percent escaped query string.

    let url = URL(string: "https://example.com")!
    var components = URLComponents(url: url, resolvingAgainstBaseURL: false)!
    
    components.queryItems = [
        URLQueryItem(name: "key1", value: "NeedToEscape=And&"),
        URLQueryItem(name: "key2", value: "vålüé")
    ]
    
    let query = components.url!.query
    

    The query will be a properly escaped string:

    key1=NeedToEscape%3DAnd%26&key2=v%C3%A5l%C3%BC%C3%A9

    Now you can create a request and use the query as HTTPBody:

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = Data(query.utf8)
    

    Now you can send the request.

提交回复
热议问题