Swfit 4 JSON adding custom header - json

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

Related

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

Why can't post JSON to server in swift?

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:

AlamoFire Request Google Cloud Prediction API iOS Parse Error

I am using AlamoFire to make POST queries to one of my models in Google Cloud Prediction. Whenever I send a request, I get back an error stating: This API does not support parsing form-encoded input.
After a bit of researching, I found that I needed to set my Content-Type HTTP header to "application/json". Hopefully, you can find something that I missed when making my request. Here is my code:
let parameters = [
"access_token" : accessToken,
"input": [
"csvInstance": [
"This is very positive"
]
]
]
Alamofire.Manager.sharedInstance.session.configuration
.HTTPAdditionalHeaders?.updateValue("application/json",
forKey: "Accept")
Alamofire.Manager.sharedInstance.session.configuration
.HTTPAdditionalHeaders?.updateValue("application/json",
forKey: "Content-Type")
Alamofire.request(.POST, "https://www.googleapis.com/prediction/v1.6/projects/mailanalysis-1378/trainedmodels/10kTweetData/predict", parameters: parameters).responseJSON { (response) in
if let JSON = response.result.value {
print("JSON: \(JSON)")
//print("refresh token = " + auth.accessToken)
}
}
In case someone is still looking for an answer, I managed to access GooglePredictionAPI from my iOS client without Alamofire:
var accessToken: String?
GIDSignIn.sharedInstance().currentUser.authentication.getTokensWithHandler { (authentication, error) in
if let err = error {
print(err)
} else {
if let auth = authentication {
accessToken = auth.accessToken
}
}
}
if let accTok = accessToken {
let parameters = [
"input": [
"csvInstance": [
0.9,
0.14,
-0.41,
1.61,
-1.67,
1.57,
-0.14,
1.15,
0.26,
-1.52,
-1.57,
3.65
]
]
]
let url = NSURL(string: "https://www.googleapis.com/prediction/v1.6/projects/ExermotePredictionAPI/trainedmodels/getExercise/predict")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST" //set http method as POST
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("Bearer \(accTok)", forHTTPHeaderField: "Authorization")
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: AnyObject] {
print(json)
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
}

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)")
}
}