Why can't post JSON to server in swift? - json

I able to post the param JSON to server by POSTMAN, but can't post it in this swift code. why?
and my console have this error
A1AD-41C2-955D-4E000D35C5CC>.<4> finished with error - code: -1002
let param = [["cid": "5","accbookname" : "fromiOS2","accbooktype": "test","category": "test","user": "test"]] as [[String : Any]]
let headers = [
"content-type": "application/json",
"cache-control": "no-cache"
]
if let postData = (try? JSONSerialization.data(withJSONObject: param, options: [])) {
let serverUrl = "x-cow.com/finnciti/scripts/updateAccountBook.php"
let request = NSMutableURLRequest(url: URL(string: serverUrl)!,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData
print(String(data: postData, encoding: .utf8)!)
//[{"cid":"5","user":"test","accbooktype":"test","accbookname":"fromiOS2","category":"test"}]
//can post this on postman
let task = URLSession.shared.dataTask(with: request as URLRequest) {
(data, response, error) -> Void in
DispatchQueue.main.async(execute: {
if error != nil {
print("failed!!!\(error!.localizedDescription)")
//failed!!!unsupported URL
return
}
....
[{"cid":"5","user":"test","accbooktype":"test","accbookname":"fromiOS2","category":"test"}]

I think your URL is not correct.
Try adding http:// before your URL and final URL will be:
http://x-cow.com/finnciti/scripts/updateAccountBook.php
EDIT:
I have tested your code with that and it's working. Check below screenshot:

Related

MVC Json Parsing - Swift

I get json output from the MVC project. You can see this output in the image below. But I cannot draw this output on the swift side. For example, I sent the value 6 to the id parameter and got the output in postman. Likewise, how can I pull this data on the swift side?
#objc func gorselCEK(){
let url = URL(string: ".../MobilService/KategoriGorsel/")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "id=\(6)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
return
}
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject]
if let json = try JSONSerialization.jsonObject(with: data) as? [String: String],
let sifre = json[""] {
//Doesn't go in here
}
} catch let parseError {
print("parsing error: \(parseError)")
let responseString = String(data: data, encoding: .utf8)
print("raw response: \(responseString)")
}
}
task.resume()
}
In the postman, it is GET request and in Swift, you're trying to make a POST request.
Change request method to GET
request.httpMethod = "GET"
Update URL with QueryItems
var urlComponent = URLComponents(string:".../MobilService/KategoriGorsel/")!
url.queryItems = [
URLQueryItem(name: "id", value: "6")
]
//Request
var request = URLRequest(url: urlComponent.url)
request.httpMethod = "GET"
No need to set httpBody

HTTP Authentication request with Campaign Monitor in Swift

I am trying to post user data to Campaign Monitor when they sign up in my app. Can anyone help me add the authorisation to the request. I currently get this error:
Optional("{\"Code\":50,\"Message\":\"Must supply a valid HTTP Basic
Authorization header\"}")
my code:
let parameters = [ "FirstName1": "test",
"SecondName": "test",
"email": "test#test.com"
]
let clientID = "52bb93ac4d9a3f261abcda0123456789"
let url = URL(string: "https://api.createsend.com/api/v3.2/clients.json")!
var request = URLRequest(url: url)
request.httpMethod = "Post"
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
// add the API Key to the request / security
request.setValue(clientID, forHTTPHeaderField: "username") // IS THIS RIGHT??
// THiS WAS HOW I CREATED CORRECT AUTHORIZATION
let APIKey = "0069b38c27b3e44de0234567891011"
let listID = "5e61fde130969d561dc0234567891011"
let url = URL(string: "https://api.createsend.com/api/v3.2/subscribers/\(listID).json")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
// add the API Key to the request / security
let loginString = "\(APIKey)"
let loginData = loginString.data(using: String.Encoding.utf8)
let base64LoginString = loginData!.base64EncodedString()
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
// THEN CAN SET UP THE SESSION
let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) {
(data, response, error) in
if error != nil {
print("Error is: \(String(describing: error))")
}
if let response = response {
let nsHTTPResponse = response as! HTTPURLResponse
let statusCode = nsHTTPResponse.statusCode
print("status code = \(statusCode)")
}
if let data = data {
let postResponse = String(data: data, encoding: .utf8)
print("responseString = \(String(describing: postResponse))")
}
}
task.resume()
In this line:
// add the API Key to the request / security
request.setValue(clientID, forHTTPHeaderField: "username") // IS THIS RIGHT??
It's not correct, even they told you why. You need a Basic Auth Header
For POST requests in Swift, generally you have to set the following:
request.setValue("Basic " + clientID, forHTTPHeaderField: "Authorization") // is clientID your access token?
Good luck

Send post request with bearer token and json body in Swift

I'm pretty new to swift and i tried to make a post request to a website, but couldn't come up with an working result, yet. All examples I found didn't work for me either.
I need to send a json body to https://mypostrequestdestination.com/api/
The json body only contains of one value
{State:1}
And the Header has to contain
{"Authorization": bearer "token"}
{"Accept":"application/json"}
{"Content-Type":"application/json"}
Hope someone can help me.
Thanks!
This one worked for me
let token = "here is the token"
let url = URL(string: "https://mypostrequestdestination.com/api/")!
// prepare json data
let json: [String: Any] = ["State": 1]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
// create post request
var request = URLRequest(url: url)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = jsonData
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.setValue( "Bearer \(token)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
print(responseJSON)
}
}
task.resume()

Swfit 4 JSON adding custom header

How can I add custom header while sending GET request on server.
I have tried
var request = URLRequest(url: URL(string: URL)!)
request.httpMethod = "GET"
// request.addValue("2", forHTTPHeaderField: "x-api-version")
request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Accept")
P.S I am beginner so if there is any mistake please point it out and help me to improve. Thank you in advance.
If your purpose is to authenticate to the API using a token, you set the wrong format for the Authorization header. Token authorization is also called "bearer authorization", the format is below:
let url = URL(string: "https://httpbin.org/get")!
let token = "abcdef"
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
URLSession.shared.dataTask(with: request) { data, response, error in
guard error == nil else { print(error!); return }
guard let data = data else { print("No data"); return }
if let str = String(data: data, encoding: .utf8) {
print(str)
}
}.resume()
You don't need the Content-Type header since a GET request has no body content.
Try below code:
func setHeader() -> [String : String] {
let dictionary = [
"Accept":"application/json",
"Content-Type":"application/json",
"Authorization": "your_authtoken"
// more headers here
]
return dictionary
}
// calling
request(endPoint, method: .post, parameters: params, encoding:JSONEncoding.default, headers: setHeader())

How to POST JSON data using NSURLSession in swift

I am stuck with the below code. How do I set the param and in post method?
let params:[String:Any] = [
"email" : usr,
"userPwd" : pwdCode]
let url = NSURL(string:"http://inspect.dev.cbre.eu/SyncServices/api/jobmanagement/PlusContactAuthentication")
let request = NSMutableURLRequest(URL: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = params<what should do for Json parameter>
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
println("response was not 200: \(response)")
return
}
}
if error {
println("error submitting request: \(error)")
return
}
// handle the data of the successful response here
}
task.resume()
if I understand the question correctly
var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: configuration)
var usr = "dsdd"
var pwdCode = "dsds"
let params:[String: AnyObject] = [
"email" : usr,
"userPwd" : pwdCode ]
let url = NSURL(string:"http://localhost:8300")
let request = NSMutableURLRequest(URL: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.allZeros, error: &err)
let task = session.dataTaskWithRequest(request) {
data, response, error in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
println("response was not 200: \(response)")
return
}
}
if (error != nil) {
println("error submitting request: \(error)")
return
}
// handle the data of the successful response here
var result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as? NSDictionary
println(result)
}
task.resume()
I would suggest using AFNetworking. See for example, Posting JSON data using AFNetworking 2.0.
This is how you can set parameters and send a POST request, easy approach using Alamofire.
Swift 2.2
let URL = NSURL(string: "https://SOME_URL/web.send.json")!
let mutableURLRequest = NSMutableURLRequest(URL: URL)
mutableURLRequest.HTTPMethod = "POST"
let parameters = ["api_key": "______", "email_details": ["fromname": "______", "subject": "this is test email subject", "from": "support#apple.com", "content": "<p> hi, this is a test email sent via Pepipost JSON API.</p>"], "recipients": ["_________"]]
do {
mutableURLRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions())
} catch {
// No-op
}
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
Alamofire.request(mutableURLRequest)
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}