Here some code:
var URL: NSURL = NSURL(string: "http://stackoverflow.com")
var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
request.HTTPBody = ??????
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
What should I write in request.HTTPBody
if I want send POST query "key" = "value"
?
In a POST request, the parameters are sent as a body of the request, after the headers. To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.
Creating a Data Task Let's use the URLSession API to perform an HTTP request. The objective is to fetch the data for an image. Before we start, we need to define the URL of the remote image. import UIKit let url = URL(string: "https://bit.ly/2LMtByx")!
The most commonly used HTTP request methods are GET, POST, PUT, PATCH, and DELETE. These are equivalent to the CRUD operations (create, read, update, and delete). GET: GET request is used to read/retrieve data from a web server.
No different than in Objective-C, HTTPBody expects an NSData object:
var bodyData = "key1=value&key2=value&key3=value" request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
You'll have to setup the values & keys yourself in the string.
Update to Swift 4.2
This code is based on pixel's answer, and is meant as an update for Swift 4.2
let bodyData = "key1=value&key2=value&key3=value"
request.httpBody = bodyData.data(using: .utf8)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With