Is there a different way how to send a HTTP "POST" request without using third party libraries using custom header and body? - ios

I am trying to send a HTTP "POST" request for a web-service that should return a base64 encoded picture. This is an example HTTP request for the service:
I am trying the following:
func fetchPicture(username: String, password: String) {
let url = URL(string: "https://myurl.com/download/bootcamp/image.php")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.setValue(password.stringToSHA1Hash(), forHTTPHeaderField: "Authorization")
let postString = "username=\(username)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
}
I am getting an error 401 Unauthorized, I don't actually know whether it is because my request is bad all together or just the login initials. It would be grand if someone could go over the code and tell me if it actually corresponds to the request example shown above.
Thanks!

The first thing I notice is that you aren’t setting the request HTTP Method:
request.httpMethod = “POST”

As it turns out, I was using the CommonCrypto hashing function wrongly, I ended up using this instead:
https://github.com/apple/swift-package-manager/blob/master/Sources/Basic/SHA256.swift
And the SHA256 hash it returned was the correct one I needed, maybe this might help someone in the future.

Related

How to get JSON data with HTTP Post method in swift 3?

I confuse by getting HTTP response in post method. when i check response on postman, then the required response is got and profile updated successfully. But in programmatically i got error notice. What was the problem? how to solve it? please, refer screenshots. Thanks in advance!
Code i have try
override func viewDidLoad() {
super.viewDidLoad()
self.updateDetails()
}
func updateDetails()
{
let postString = "api=update_people&user_id=18&email=rajesh#gmail.com&first_name=Raejsh&phone=456562&age=26&gender=male&blood_group=A"
print(postString)
// let alertMessage = alert()
let url = NSURL(string: "http://kuruthi.in/portal/api/register")
let request = NSMutableURLRequest(url: url as! URL)
request.httpBody = postString.data(using: String.Encoding.utf8)
request.httpMethod = "POST"
request.addValue("123456", forHTTPHeaderField: "X-API-KEY")
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request as URLRequest) { data,response,error in
guard error == nil && data != nil else
{
print("Error:\(error)")
return
}
let httpStatus = response as? HTTPURLResponse
if httpStatus!.statusCode == 200
{
if data?.count != 0
{
let responseString = String(data: data!, encoding: .utf8)
print(responseString)
}
else
{
print("No data got from url!")
}
}
else
{
print("error httpstatus code")
}
}
task.resume()
}
Response in Program output :
Response in postman:
The reason you are getting html code is that you are receiving some error from your web services look at the message "A PHP Error was encountered" in your output log.
The success in postman is because your request is in form-data. Compare the request from postman from Raw with the request you are generating.
You can refer this link for creating a request. But the code is in Objective-Cand you can use this link to convert the code, or you can use Alamofire to create requests and refer this link for creating multipart form-data requests using Alamofire

NSMutableURLRequest POST 405 error Get

I know there are similar questions on stack overflow but nothing has solved my issue.
I'm making a simple NSMutableRequest to a url and posting a simple string:
let locationString = "myString"
let request = NSMutableURLRequest(URL: NSURL(string: "http://exampleurl.com")!)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
request.HTTPBody = locationString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
but I'm getting a 405 error: "Method GET not allowed"
Not sure what I'm doing wrong
Thanks
I found a solution, temporary at least until I can get the server side code changed to accept a JSON object regardless of order.
I constructed the JSON as a string with the correct order, used the method above and it works.

Why Authorization header gets removed in iOS PATCH requests?

there. I got a very strange problem. The thing is that when i'm trying to send PATCH requests server says that no Authorization header contains token. The same for PUT request.Tried to sniff and found out that no Authorization header is sent at all. While any other types of request contain Authorization header. First thought its Alamofire framework specific problem, but using NSURLConnection requests and NSURLSession tasks gave me the same: NO AUTHORIZATION HEADER IS SENT!
Here is my code used for Alamofire:
Alamofire.request(.PATCH, path, parameters: ["email":"new#mail.com"], encoding: .JSON, headers: ["Authorization":"token \ ((User.sharedUser().token)!)"]).validate().responseJSON { (response) in
if response.response?.statusCode == 200{
print("success")
}else{
print("Error")
}
}
and here is code with NSURLConnection:
let request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
request.HTTPMethod = "PATCH"
request.addValue("\(token)", forHTTPHeaderField: "authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
do{
let bodyData = try NSJSONSerialization.dataWithJSONObject(["email":"nuv#gmail.com"], options: [])
request.HTTPBody = bodyData
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
if let mdata = data {
let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
print(contents)
} else {
print(error?.localizedDescription)
}
}
}catch{
print("failed serialization")
}
IIRC, the Authorization header is one of those headers that NSURLSession reserves for its own purposes, and may overwrite with its own values—particularly if you're sending something that looks like normal HTTP authentication.
Can you send an X-Authorization header instead?
Anyone who is looking for Alamofire 5(AF 5) solution here's the solution:
let headers: [String:String] = [...]
let params: [String: Any] = [...]
let url = URL(...)
let redirector = Redirector(behavior: Redirector.Behavior.modify({ (task, urlRequest, resp) in
var urlRequest = urlRequest
headers.forEach { header in
urlRequest.addValue(header.value, forHTTPHeaderField: header.key)
}
return urlRequest
}))
//use desired request func of alamofire and your desired enconding
AF.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers)
.responseJSON { response in
//handleDataResponse...
}.redirect(using: redirector)

INPUT_VALIDATION_ERROR in BetFair Login API / iOS

I am getting INPUT_VALIDATION_ERROR while logging into betfair api. I am following the docs, but it was of no use with this particular error code.
I'd appreciate if anyone could guide me in the right direction.
Here is my swift code
let request = NSMutableURLRequest(URL: NSURL(string: "https://identitysso.betfair.com/api/login")!)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("MY_APP_KEY", forHTTPHeaderField: "X-Application")
let postString = "username=MY_USER_NAME&password=MY_PASSWORD"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
I think you need to set header in http for Content-Type as
application/x-www-form-urlencoded
Three parameters in Http header:
httpRequest.setHeader("Accept", "application/json");
httpRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.setHeader("X-Application", <apiKey>);

Swift: Adding Headers to my REST POST Request

I am still learning Swift and I am trying to make a POST request to my web service via my new iOS App written in Swift.
I need to know how to add 2 headers to my already existing code. Also am I adding the parameters correctly?
What I have so far:
let myUrl = NSURL(string: "https://MY-MOBILE-SERVICE.azure-mobile.net/api/login");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
// Compose a query string
let postString = "email=myemail#website.com&password=123";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
print("response = \(response)")
}
task.resume()
Here are the Headers I need to add to this request:
X-ZUMO-APPLICATION: 45634243542434
ACCEPT: application/json
How do I attach these headers to my request?
Have a look at the reference docs:
https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSMutableURLRequest_Class/#//apple_ref/occ/instm/NSMutableURLRequest/setValue:forHTTPHeaderField:
so you would do: request.setValue("ACCEPT" forHTTPHeaderField: "application/json")
if you use alamofire, this should work, it also eases things for you so you choose get or post
var pars2 : Dictionary<String,String> = ["api_key":"value"]
Alamofire.request(.POST, "someURLString" ,parameters: pars2).responseJSON()
{
(request, response, data, error) in
if(data != nil)
{
self.countryIDArray.removeAll(keepCapacity: false)
var status = data!["status"]!! as! String
}
}

Resources