NSMutableURLRequest POST 405 error Get - ios

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.

Related

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

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.

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>);

send post variables to my Api

I am trying to send post parameters to my API, it gets 4 variables :
labelled
id_produit
id_magasin
Prix
Here's my code:
#IBAction func AddProduct(sender: AnyObject) {
let myUrl = NSURL(string: "http://vps43623.ovh.net/yamoinscher/api/products/create_product");let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
// Compose a query string
let postString = "id=123456789&libelle=Florida&id_magasin=1&prix=1500";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
// print out response object
print("response = \(response)")
// Print out response body
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
}
And when I execute this code I get this response:
response = Optional(<NSHTTPURLResponse: 0x7fadeaf532a0> { URL: http://vps43623.ovh.net/yamoinscher/api/products/create_product } { status code: 200, headers {
Connection = "keep-alive";
"Content-Length" = 0;
"Content-Type" = "application/x-www-form-urlencoded";
Date = "Thu, 28 Apr 2016 09:15:09 GMT";
"MS-Author-Via" = DAV;
Server = nginx;
"X-Powered-By" = PleskLin;
} })
responseString = Optional()
The console tells me that there is no variables sent to the api. Can any one help me please?
#IBAction func AddProduct(sender: AnyObject) {
let myUrl = NSURL(string: "http://vps43623.ovh.net/yamoinscher/api/products/create_product");let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
// Compose a query string
let postString = "id=123456789&libelle=Florida&id_magasin=1&prix=1500";
let postLength = String(postData.length)
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
// print out response object
print("response = \(response)")
// Print out response body
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
}
Your response is in your data object. so, convert that data in approriate response format. Ask your web service provider that your response format is string, if yes then your code seems to be right but if your response is in json format then you should convert your data in json object with jsonserialization. so check this, because your status code is 200 means ok. so,there is no problem in code i think except response serialization. Try to convert data in json or try to convert it in string with different reading option which one is appropriate.
hope this will help :)

Swift 2.0 POST Body null

Using a packet analyzer, I'm getting that my HTTP body is null. Is there any reason why my params aren't getting sent in the POST request?
let request = NSMutableURLRequest(URL: NSURL(string:"SERVERURL")!)
request.HTTPMethod = "POST"
do {
let params = ["returnInt":"5"] as Dictionary<String,String>
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.PrettyPrinted)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
} catch {
//Do nothing
}
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if error != nil{
print("error=\(error)")
return
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("\(responseString)")
}
task!.resume()
As I saw with println() in the Playground, the request.HTTPBody is not nil. Also, my analyzer shows not nil either:

HTTP Request with Body using PATCH in Swift

I'm trying to send a Patch request with a serialized JSON Body.
For some reason the server is not able to receive the body properly. I have a feeling that there seems to be a problem with the PATCH method in combination with the http request body.
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
var URL = B2MFetcher.urlForBooking(event.unique, bookingID: booking.unique)
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = "PATCH"
// Headers
println(token)
request.addValue(token, forHTTPHeaderField: "Authorization")
request.addValue("gzip, identity", forHTTPHeaderField: "Accept-Encoding")
// JSON Body
let bodyObject = [
"op": "cancel"
]
var jsonError: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(bodyObject, options: nil, error: &jsonError)
/* Start a new Task */
let task = session.dataTaskWithRequest(request, completionHandler: { (data : NSData!, response : NSURLResponse!, error : NSError!) -> Void in
completion(data: data, response:response , error: error)
})
task.resume()
You could try to add a Content-Type header to the request:
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
or use one of the other JSON Content-Type formats described here.
I tested it with an ExpressJS server and without the Content-Type header the server got an empty body, but with a Content-Type header it worked well.
in swift 3/4 :
let request = NSMutableURLRequest(url: NSURL(string: "http://XXX/xx/xxx/xx")! as URL)
request.httpMethod = "PATCH"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
do{
let json: [String: Any] = ["status": "test"]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
request.httpBody = jsonData
print("jsonData: ", String(data: request.httpBody!, encoding: .utf8) ?? "no body data")
} catch {
print("ERROR")
}
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(error)")
completion(false)
return
}
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("responseString = \(responseString)")
completion(true)
return
}
task.resume()
Simple Way to use patch without using HTTPBody
If you want to just use patch, you just need to change the value of the name of a specific user then it will be like:
let myurl = URL(string: "https://gorest.co.in/public-api/users/"+"\(id)?"+"name=abc")!
var request = URLRequest(url:myurl)
request.addValue("Bearer yourAuthorizationToken",forHTTPHeaderField:"Authorization")
request.httpMethod = "PATCH"
let dataTask = URLSession.shared.dataTask(with: request)
dataTask.resume()
Note: here "id" will be userId

Resources