Swift HTTP POST Request Login - html

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
}

Related

How to load HTML string on UIWebView using swift?

The Following is the Code I am using to load HTML String on web view:-
let urlAsString = "https://here is my url"
var encryptedStr: String = "merchant_id=\(merchantId)&order_id=\(orderId)&redirect_url=\(redirectUrl)&cancel_url=\(cancelUrl)&language=EN&billing_name=\(billingName)&billing_address=\(billingAddress)&billing_city=\(billingCity)&billing_state=\(billingState)&billing_zip=\(billingZipCode)&billing_country=\(billingCountry)&billing_tel=\(billingTel)&billing_email=\(billingEmail)&delivery_name=\(deliveryName)&delivery_address=\(deliveryAddress)&delivery_city=\(deliveryCity)&delivery_state=\(deliveryState)&delivery_zip=\(deliveryZipCode)&delivery_country=\(deliveryCountry)&delivery_tel=\(deliveryTel)&merchant_param1=additional Info.&merchant_param2=additional Info.&merchant_param3=additional Info.&merchant_param4=additional Info.&payment_option=\(payOptId)&card_type=\(cardType)&card_name=\(cardName)&data_accept=\(dataAcceptedAt)&enc_val=\(encVal!)&issuing_bank=\(issuingBank)&access_code=\(accessCode)&mobile_no=\(mobileNo)&emi_plan_id=\(emiPlanId)&emi_tenure_id=\(emiTenureId)"
print("encryptedStr :: ",encryptedStr)
if isSaveCard!
{
encryptedStr = encryptedStr + ("&saveCard=Y")
}
let myRequestData = NSData(bytes: encryptedStr, length: encryptedStr.lengthOfBytes(using: .utf8))
print("\n\n\n myRequestData :: ",myRequestData.description)
let request: NSMutableURLRequest = NSMutableURLRequest(url: URL(string: urlAsString)!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type")
request.setValue(urlAsString, forHTTPHeaderField: "Referer")
request.httpMethod = "POST"
request.httpBody = myRequestData as Data
print("\n\n\nwebview :: ",request)
let transResData: Data? = try? NSURLConnection.sendSynchronousRequest(request as URLRequest, returning: nil) // here i am not getting any data
print("transResData ::: \(String(describing: transResData))")
let transResString = String(data: transResData!, encoding: String.Encoding.ascii)
print("\n\n\n*******************************Payload Response Start*******************************\n")
print("\(String(describing: transResString))") // it gives blank space no any HTML Code
print("\n**********************************Payload Response End********************************\n\n\n")
viewWeb.loadHTMLString(transResString!, baseURL: nil)
But not getting any data in variable named transResData. It gives 0 Bytes as Output. Please provide any Code that can Help me in getting Output.
TIA.

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

Global functions to post and get API data in swift

I am trying to make my POST and GET API request methods global so that I need not repeat the call procedure repetitively. For this, I created a swift file and made two functions for POST API and GET API, but can't figure out how to pass data from calling class to the called class, and return back the response to the calling class. My code which needs to be integrated in a separate swift file is :
let request = NSMutableURLRequest(URL: NSURL(string: "http://api.quickblox.com/users.json")!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("0.1.1", forHTTPHeaderField: "QuickBlox-REST-API-Version")
request.setValue(tokenSet, forHTTPHeaderField: "QB-Token")
request.HTTPMethod = "POST"
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(dict, options: [])
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()
I need to pass API Url and a request data in the form of a dictionary, to, say postApiRequest() and getApiRequest() methods. How do I create swift file for the same and call it elsewhere.

Parameters in JSON POST Request ignored in Swift?

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?

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.