Swift post request error 500 - swift

Im trying to post a http request with parameters, the response is XML Formatted.
see: https://www.codepunker.com/tools/http-requests/64243-brrjq9t
now, when I try to code that im always getting the same error 500. what I do wrong?
guard let url = URL(string: "http://www.nakdan.com/GetResult.aspx") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
var bodyData = "txt=מה קורה&usr=&pass=&ktivmale=false"
request.httpBody = bodyData.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request as URLRequest){
data,response, error in
print(response!)
if error != nil{
print("error")
return
}
}
task.resume()

Related

Swift POST to api

I have an odd issue and I am hoping you guys can help me.
The Task:
I want to post json to a API rest call.
And I am sure the rest API works - I have copied the json from print() in Swift and tried it in postman, and the works just fine.
When I try to post via Swift i get 400 Bad request.
The code:
func postMobileContacts(serverURL: String, jsonToPost: String){
// Prepare URL
let url = URL(string: serverURL)
guard let requestUrl = url else { fatalError() }
// Prepare URL Request Object
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
// Set HTTP Request Body
request.httpBody = Data(jsonToPost.utf8);
// Set HTTP Request Header
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Authorization", forHTTPHeaderField: String(data: KeychainHelper.standard.read(service: "access-token", account: "store")!, encoding: .utf8)!)
// Perform HTTP Request
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
// Check for Error
if let error = error {
print("Error took place \(error)")
return
}
// Convert HTTP Response Data to a String
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("Response data string:\n \(dataString)")
}
}
task.resume()
}
This line is definitely wrong:
request.setValue("Authorization", forHTTPHeaderField: String(data: KeychainHelper.standard.read(service: "access-token", account: "store")!, encoding: .utf8)!)
it should be the other way around.
request.setValue(String(data: KeychainHelper.standard.read(service: "access-token", account: "store")!, encoding: .utf8)!, forHTTPHeaderField: "Authorization")
You mixed up the value with the header name.
Made some edits to your code
Currently the data is not directly sent to the request as said in comments.
JSONEncodable can be send to the request after encoding to data.
func postMobileContacts(serverURL: String, jsonToPost: Encodable) { //<--here
// Prepare URL
let url = URL(string: serverURL)
guard let requestUrl = url else { fatalError() }
let data = try! JSONEncoder().encode(jsonToPost) //<-Changed here
// Prepare URL Request Object
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
// Set HTTP Request Body
request.httpBody = data; //<-- and here
// Set HTTP Request Header
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Authorization", forHTTPHeaderField: String(data: KeychainHelper.standard.read(service: "access-token", account: "store")!, encoding: .utf8)!)
// Perform HTTP Request
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
// Check for Error
if let error = error {
print("Error took place \(error)")
return
}
// Convert HTTP Response Data to a String
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("Response data string:\n \(dataString)")
}
}
task.resume()
}

Trying to fetch some data from API in swift, and I am getting lost, what am I doing wrong?

Trying to get AI generated text from deepai.com
the example they provided looks like this:
curl \
-F 'text=YOUR_TEXT_HERE' \
-H 'api-key:quickstart-QUdJIGlzIGNvbWluZy4uLi4K' \
https://api.deepai.org/api/text-generator
and I'm trying to reproduce the same in swift:
var request = URLRequest(url: url)
request.setValue("quickstart-QUdJIGlzIGNvbWluZy4uLi4K", forHTTPHeaderField: "api-key")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let body = ["text": "Donald Trump"]
let bodyData = try? JSONSerialization.data(withJSONObject: body, options:[])
request.httpMethod = "POST"
request.httpBody = bodyData
URLSession.shared.dataTask(with: request){ (data, responce, error) in
print(responce!)
if let error = error {
print(error)
} else if let data = data {
print(data)
}
}.resume()
I get status code 400. Don't get deep into my optionals unwrapping and so on. Just tell what am I doing wrong? Why curl works and my swift code doesn't?
UPDATE
tried the solution from the suggested question/answer concerning multipart form-data, still not working. Please take a look
var request = URLRequest(url: url)
let boundary = UUID().uuidString
request.setValue("quickstart-QUdJIGlzIGNvbWluZy4uLi4K", forHTTPHeaderField: "api-key")
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let body = ["text": "Donald Trump"]
var data = Data()
for(key, value) in body{
// Add the reqtype field and its value to the raw http request data
data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
data.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: .utf8)!)
data.append("\(value)".data(using: .utf8)!)
}
data.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)
request.httpMethod = "POST"
//request.httpBody = data
URLSession.shared.uploadTask(with: request, from: data){ (data, responce, error) in
print(responce!)
if let error = error {
print(error)
} else if let data = data {
print(data)
}
}.resume()
Don't be mad with my stupidity!)

error to send Authorization headers in swift 3 don't work, (the server dont' receive the Authorization headers )

I have the problem, my server doesn't receive the header Authorization,
I try with this code but doesn't work.
This is my code:
let token: String? = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1MjE3NDc3OTYsImV4cCI6MTUyNDMzOTc5NiwiZGF0YSI6eyJpZCI6IjM2IiwiaWRfZW1wcmVzYSI6IjEiLCJub21icmVzIjoiU2VyZ2lvIEFsZWphbmRybyIsImFwZWxsaWRvX3BhdGVybm8iOiJSb3NhZG8iLCJhcGVsbGlkb19tYXRlcm5vIjoiQXp1bCIsInpvbmFfaG9yYXJpYSI6IkFtZXJpY2FcL01lcmlkYSIsImlkX3BlcmZpbCI6IjEiLCJjb3JyZW8iOiJydXNzZWxhbGV4aXMxMjNAZ21hLmNvbSIsInVzZXJuYW1lIjoiZW1wbGVhZG9kZW1vIiwicGFzc3dkIjoiKkE0QjYxNTczMTkwMzg3MjRFMzU2MDg5NEY3RjkzMkM4ODg2RUJGQ0YiLCJhY3Rpdm8iOiIxIiwiZmhfY2FwdHVyYSI6IjIwMTctMDItMjAgMjE6MDI6NTUiLCJkb21pY2lsaW8iOiIiLCJjcCI6IiIsInRlbGVmb25vIjoiIiwidXN1YXJpbyI6IjEiLCJpcCI6IjE4OS4xNTAuMTQxLjExNyJ9fQ.79HJPR04IjHBwLzpeUnjJel0UAYSG0rtqPvOPca7Uds"
guard let name = token, !name.isEmpty else { return }
let url = URL(string: "http://dev.viupruebas.com.mx/webservice/test/getvehiculos")
var request = NSMutableURLRequest(url: url!)
request.httpMethod = "GET"
request.setValue("Bearer \(name)", forHTTPHeaderField: "Authorization")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
i resolve my problem read the nex line:
let task = URLSession.shared.dataTask(with: request) { data, response,
error in
my finaly code is:
let token: String? = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1MjE4MjY2MTgsImV4cCI6MTUyNDQxODYxOCwiZGidXN1YXJpbyI6IjEiLCJpcCI6IjE4Ny4xNTUuOTIuMjEzIn19.pu6_1LmfxliXke_WMY82hEKy0Dsn1fk-feaTKnfGpbo"
guard let name = token, !name.isEmpty else { return }
//url
let url = URL(string: "http:/webservice")!
var request = URLRequest(url: url)
request.addValue("\(name)", forHTTPHeaderField: "Authorization")
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { data, response, error in

URLSession returns HTTP 403 error page

I'm trying to run a HTTP Request in Swift, to POST 2 parameters to a URL.
But it always returns 403 error page, what's wrong?
I trying adding Content-type header, but it doesn't work.
Code:
print("ENVIAR DATOS")
let url = NSURL(string: "https://www.portaljuridico.com.co/portaljuridico/User/login")
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST"
let param = ["username" : "juan", "password" : "123"]
guard let httpBody = try? JSONSerialization.data(withJSONObject: param, options: []) else { return }
//request.addValue("application/form-data", forHTTPHeaderField: "Content-Type")
//request.setValue("application/json", forHTTPHeaderField: "Content-Type")
//request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = httpBody
let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
guard let data = data, error == nil else {
print("error = \(error!)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response!)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString!)")
}
task.resume()
Endpoint appears to be http://www.portaljuridico.com.co/portaljuridico/User/loginUser and redirects to http://www.portaljuridico.com.co/portaljuridico/Login on invalid user/password.

NSURLSession parameters not recognized

Im attemping to make a HTTPRequest using NSURLSession. When I set the full url the request returns the correct data but when using parameters (NSJSONSerialization.dataWithJSONObject -> HTTPBody I get this error
error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."
is there something im doing wrong here?
let json = ["api_key": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"]
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)
let url = NSURL(string: "https://api.themoviedb.org/3/discover/movie")!
let request = NSMutableURLRequest(URL: url)
request.HTTPBody = jsonData
request.HTTPMethod = "GET"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
if error != nil{
print("Error -> \(error)")
return
}
do {
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]
print("Result -> \(result)")
} catch {
print("Error -> \(error)")
}
}
task.resume()
} catch {
print(error)
}
}
This is not a duplicate! I looked at the suggested answer (none of them worked) before asking this question
In your case that issue can be solved by changing the request.HTTPMethod = "GET" to request.HTTPMethod = "POST"
You should not send HTTP Body in the get request, to send the data with the body you should change HTTPMethod to post
Note: Please check if this api method supports POST requests, if it don't support post you can't use it with http body/post, as per doc i only find 'get' request for the discover/movie which can be like this:
let url = NSURL(string: "http://api.themoviedb.org/3/discover/movie?api_key=YOUR_API_KEY")!
let request = NSMutableURLRequest(URL: url)
request.addValue("application/json", forHTTPHeaderField: "Accept")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { data, response, error in
if let response = response, data = data {
print(response)
print(String(data: data, encoding: NSUTF8StringEncoding))
} else {
print(error)
}
}
task.resume()
Ref: You can check more information from this url: http://docs.themoviedb.apiary.io/#reference/discover/discovermovie/get