I searched a lot and there's no clear instruction for sending POST request with "x-www-form-urlencoded" content-type. i want to know how to do that and if you know how to do it with Alamofire it would be even better. any help will be appreciated.
In this post, we'll learn to use the HttpClient class from System.Net.Http to send HTTP requests from C# applications with x-www-form-urlencoded data. To send a post request, we should, first, create an object of the HttpClient class and use its PostAsync () method to send the actual post request.
In order to send the data in x-www-form-urlencoded format, we can use FormUrlEncodedContent class. It accepts the data as an IEnumerable of KeyValue pairs. var data = new [] { new KeyValuePair<string, string> ("name", "John Doe"), new KeyValuePair<string, string> ("email", "[email protected]"), };
Sending HTTP requests to some external endpoints using C# is something I have to do quite often in my projects. We have numerous libraries like RestSharp for this purpose. In this post, we'll learn to use the HttpClient class from System.Net.Http to send HTTP requests from C# applications with x-www-form-urlencoded data.
Also note there is no Content-Length parameter in the sample POST request but PA is reading a Content-Length 0 in the Header. I suspect it is finding no Content-Length and not going ahead.
Hope you are searching for this one or give us more explanation in code so we get it easily:
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
let parameters = [
]
Alamofire.request("urlString", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case.success(let data):
print("success",data)
case.failure(let error):
print("Not Success",error)
self.view.makeToast(message: "Server Error!!")
}
}
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