Parameters in JSON POST Request ignored in Swift? - json

I am trying to get some data from a URL which requires me to POST a JSON request. It works in the sense that I get some data back; just not the data I expected. I then used jsontest.com to test my code:
let url = NSURL(string: "http://echo.jsontest.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
do {
let params = ["echo": "abc"] as Dictionary<String, String>
//... Just make sure that 'params' is a valid JSON object
assert(NSJSONSerialization.isValidJSONObject(params))
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.PrettyPrinted)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
} catch {
print("Error")
}
let session = NSURLSession.sharedSession()
dataTask = session.dataTaskWithRequest(request, completionHandler: {
(data: NSData?, response: NSURLResponse?, error: NSError?) in
if let httpResponse = response as? NSHTTPURLResponse where httpResponse.statusCode == 200,
let data = data {
let encodedData = NSString(data:data, encoding:NSUTF8StringEncoding)
print("encodedData = \(encodedData!)")
} else {
print("Error")
}
})
dataTask?.resume()
When I run this, I see the following output from jsontest.com:
encodedData = {"": ""}
where I expected
encodedData = {"echo": "abc"}
So, do I not understand correctly whether this is how jsontest.com works, or am I doing something wrong? (Obviously, I had similar problems using other JSON services.) Any comments are appreciated.

echo.jsontest.com doesn't work with a request body but with a request url, see www.jsontest.com/#echo for details.

Turns out #Eric D is right. I found another website to test my JSON posts on and that one worked fine. So the code is basically correct after all.
I made the following changes:
let url = NSURL(string: "http://gurujsonrpc.appspot.com/guru")
let params = [ "method" : "guru.test", "params" : [ "GB" ], "id" : 123 ] as Dictionary<String, AnyObject>
and then I get the following response:
{"jsonrpc":"2.0","id":123,"result":"Hello GB!"}
Which is exactly what was expected.
Thanks!

The correct URL is http://validate.jsontest.com
Also, I don't think you are constructing the POST request body correctly. See How are parameters sent in an HTTP POST request?

Related

how can I fix this urlString error from returning nil

So my goal is to successfully send notifications to users subscribed to a specific topic with no errors. I have a function that I use to send notifications with FCM, here it is:
func sendNotificationToUser(to token: String, title: String, body: String) {
getTheSchoolID { (id) in
if let id = id {
let urlString = "https://fcm.googleapis.com/v1/projects/thenameofmyproject-41f12/messages:send HTTP/1.1"
let url = NSURL(string: urlString)!
let paramString: [String: Any] = ["message": ["topic": id,
"notification": ["title": title, "body": body],
"data": ["user": "test_id"]
]
]
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: paramString, options: [.prettyPrinted])
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(self.bearer)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
do {
if let jsonData = data {
if let jsonDataDictionary = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
NSLog("Received data:\n\(jsonDataDictionary))")
}
}
} catch let err as NSError {
print(err.debugDescription)
}
}
task.resume()
}
}
}
I found this block of code originally off a Youtube video and tested it with my iPhone and it worked beautifully, but I modified it a bit to look like this and now when this function gets ran I get an error saying the urlString is producing a nil value.
I copied the format from the documentation and just switched out the project name, but for some reason I still get errors. Is there something wrong with url that I can't see? Also, in the image I shown below, should I add the "ya29." before my bearer key or is the value just fine how it is?
Not really sure what you are trying to do, you dont trigger notifications by calling APNS/fcm API directly from client apps, anyway question is why is URL is being nil, well you can avoid it being nil if you percentile encode the url string
let urlString = "https://fcm.googleapis.com/v1/projects/thenameofmyproject-41f12/messages:send HTTP/1.1"
guard let encodedURLString = urlString.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed) else { return }
let url = URL(string: encodedURLString)! //NSURL(string: encodedURLString)!
You dont need NSURL you can use URL instead.
Why percentile encode?
Because your url has a white space between send and HTTP send HTTP and white spaces are not allowed in valid url, if you want that white space to persist in your URL you should encode it. White space will be replaced by %20

SwiftyJSON : How can I add token?

I'm using API and getting json data with SwiftyJSON. I need an add token for the API. How can I do this with SwiftyJson?
My code :
let jsonData = (NSData(contentsOfURL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/leagueTable")!)! as NSData)
var readableJSON = JSON(data: jsonData, options: .MutableContainers, error: nil)
let name = readableJSON["standings"]
Normally I'm adding token with this code when I use Swift's JSON :
let url = NSMutableURLRequest(URL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/leagueTable")!)
url.addValue("mytokenishere", forHTTPHeaderField: "X-Auth-Token")
url.HTTPMethod = "GET"
Are you making a post/put with this data? Thats would make sense.
I suppose you already have made the request to get the readable data "jsonData" contains that. Since you ndicate you dont have the json data already this would probably work.
var url = NSMutableURLRequest(URL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/leagueTable")!)
url.addValue("mytokenishere", forHTTPHeaderField: "X-Auth-Token")
url.HTTPMethod = "GET"
NSURLSession.sharedSession().dataTaskWithRequest(url, completionHandler: data, response, error in {
if error == nil {
var readableJSON = JSON(data: data, options: .MutableContainers, error: nil)
let name = readableJSON["standings"]
url.HTTPBody = try! name.rawData()
NSURLSession.sharedSession().dataTaskWithRequest(url, completionHandler: data, response, error in {
//do something with his response from getting the data
})
} else {
print(error)
}
})
This is kind of a hacky way of doing it but I think its what you are going for

Sending (POST) Json Array with Alamofire

I am trying to send an array of JSON-Objects to my server using Alamofire.
As postparameters only Dictionary<String, AnyObject> are allowed in Alamofire. So I tried to do it with an NSMutableURLRequest.
But it doesn't work, too. I am using SwiftyJSON, too.
This is what I trying, but I cant put the Array in the Body.
//testClassList: [TestClass]
let uri : String = serveraddress + "/SendClassList";
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: uri)!)
mutableURLRequest.HTTPMethod = "POST"
var header : [String:String] = createHeader();
mutableURLRequest.addValue(header["Authorization"]!, forHTTPHeaderField: "Authorization");
mutableURLRequest.addValue(header["Content-Type"]!, forHTTPHeaderField: "Content-Type");
mutableURLRequest.addValue(header["Accept"]!, forHTTPHeaderField: "Accept");
do{
mutableURLRequest.HTTPBody = JSON(testClassList);
}catch{
print(error)
}
Alamofire.request(mutableURLRequest).responseJSON { response in
if(response.response?.statusCode == 200){
let resp: String = response.result.value as! String;
completionHandler?(resp, nil);
}
}
Is there a way to post an Array direct without wrapping it into another JSON like ["list":testClassList]
(Please only Swift 2.+ Code.)
best regards

Sending custom HTTP headers in swift

I managed to fetch json from my server but now I want to add extra security by way of http headers. This is how my code barely looks like for now:
let urlPath = "http://www.xxxxxxxx.com"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
if ((error) != nil) {
println("Error")
} else {
// process json
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
println(jsonResult["user"])
}
})
The headers that I want to add to this request are the following:
uid, which holds an integer value
hash, which is a string
If it helps, I have another app built in Titanium framework which uses this syntax:
xhr.setRequestHeader('uid', userid);
xhr.setRequestHeader('hash', hash);
So, am basically looking for a Swift equivalent.
You are using dataTaskWithURL while you should use dataTaskWithRequest, that takes NSMutableURLRequest object as an input. Using this object you can set HTTP headers, HTTPBody, or HTTPMethod
let urlPath = "http://www.xxxxxxxx.com"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "GET" // make it post if you want
request.addValue("application/json", forHTTPHeaderField: "Content-Type")//This is just an example, put the Content-Type that suites you
//request.addValue(userid, forHTTPHeaderField: "uid")
//request.addValue(hash, forHTTPHeaderField: "hash")
let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
//do anything you want
})
task.resume()
I suggest you to use Alamofire for networking
https://github.com/Alamofire/Alamofire
It is written in Swift and is every easy to use. Have a look at that page.

Swift HTTP POST Request Login

Hey I'm trying to figure out this problem for quite some time so now I'm asking you guys for help.
In my Project I'm trying to send a POST request to a website with a login form to access the server.But I somehow don't manage to pass the data.
The website I'm trying to access is https://edu.sh.ch
in the Inspector of my browser I can see it needs a Post method to pass the data :
<form id="form1" name="form1" autocomplete="off" method="post" action="/uniquesigfe5a0f1f915f15b647d0b7a5306be984/uniquesig0/InternalSite/Validate.asp" onsubmit="return(SubmitForm());"></form>
here's my code:
func PostingCredentials(){
let myUrl = NSURL(string: self.manipulatedUrl)
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
// Compose a query string
let form1 = "user_name=MyUsername&password=MyPassword"
request.HTTPBody = form1.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
println("error=\(error)")
return
}
println("response = \(response)")
// You can print out response object
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
//
println("responseString = \(responseString)")
}
task.resume()
}
Note that self.manipulateUrl equals to the url which shows up when I log in normally and submit my credentials (https://edu.sh.ch/uniquesigfe5a0f1f915f15b647d0b7a5306be984/uniquesig0/InternalSite/Validate.asp)
The Post Function posts something but the response is always some sort of error page( I'm not getting any error in the code but the response of the server is an error)
So for the end my main question are :
whats the problem with my code
where do I have to send my POST method to,to the login page url or the validation url?
Thanks in advance
Some Problem with your webpage. Something is wrong in web coding. Then also you can try below code :
let form1 = "user_name=MyUsername&password=MyPassword"
let request:NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: "https://edu.sh.ch")!)
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-type")
request.HTTPBody = form1.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in
var str = NSString(data: data, encoding: NSUTF8StringEncoding)
//var dict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSArray
}