How to make CONNECT call in iOS? - ios

NSURLSession supports POST and GET; does it also support CONNECT?
If so, what is the exact syntax?
Thanks!

Use NSMutableURLRequest to set whatever HTTP method you want
let session = NSURLSession()
guard let url = NSURL(string: "http://www.google.com") else {
fatalError("Error creating NSURL for http://www.google.com")
}
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "CONNECT"
let task = session.dataTaskWithRequest(request)
task.resume()

Related

Swift - urlsession cookies

I have a php webAPI which works well and I want to login with that in my app. I want to use cookies for that. So, I save the cookies when the user signs in and that works. I store it in userdefaults when I want to use only place cookies into HTTPCookieStorage.shared.
I try to use this for my new request, and my question is how can I add the cookies to my request?
I tried this but it's not working...
let cookiesArray = HTTPCookieStorage.shared.cookies
print(cookiesArray)
//HTTPCookieStorage.shared.setCookies(cookiesArray!, for: url, mainDocumentURL: url)
let headers = HTTPCookie.requestHeaderFields(with: cookiesArray!)
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.httpShouldHandleCookies = true
urlRequest.httpBody = postString.data(using: String.Encoding.utf8)
urlRequest.allHTTPHeaderFields = headers
//urlRequest.setValue("PHPSESSID=oe22uf92poc5c7s23u4ukl83g0", forHTTPHeaderField: "Cookie")
//URLSessionConfiguration().httpCookieAcceptPolicy = .always
let session = URLSession.shared
session.configuration.httpCookieStorage = HTTPCookieStorage.shared
session.configuration.httpCookieAcceptPolicy = .always
session.configuration.httpShouldSetCookies = true
session.configuration.httpAdditionalHeaders = headers
let task = session.dataTask(with: urlRequest) { (data, response, error) in
print(data)
print(response)
print(error)
print("itt az end\n")
}
task.resume()
I can't comment yet, but I agree that more info is needed. If you are getting errors those would be helpful to post. Also, what you are getting for your
data
response
error
would be helpful.
Other than that, I would first look at setting up Charles as an HTTP Proxy so you can see exactly what is happening when you make the request. Knowing what response you are receiving will let you know what is going wrong.
https://www.charlesproxy.com/

Unable to read data while making request

here i am getting strange issue like i can able to make request into simulator but in real device gave error like "unable to read data" also attached screen shot
My Code :
let urlPath: String = url_to_request
let url:NSURL = NSURL(string: urlPath)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

sendAsynchronousRequest was deprecated in iOS 9 (Swift 2) - Transfer Code?

I'm using XCode 7.3. Here is my code:
func postToServerFunction() {
let url: NSURL = NSURL(string: "http://mytesturl.com")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
//let textfeld = String(UserTextField.text)
let bodyData = "data=" + UserTextField.text!
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in}}
This works fine and my php-Script gets the string it should. But there is the
sendAsynchronousRequest was deprecated in iOS 9
message.
As I read, with Swift 2 the method has changed.
I searched a lot for this error, but I'm not able to convert the code that it matches to Swift 2. As I also read, i should use something like this
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request)
but I can't get it down. And actually, I don't understand every single line. I wrote the code myself, but from some examples that it works for me.
This is the most basic way you'd use a shared session:
if let url = NSURL(string: "http://mytesturl.com"),
userField = UserTextField.text {
let request = NSMutableURLRequest(URL: url)
let bodyData = "data=" + userField
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request,completionHandler: {(data,response,error) in
}
)
dataTask.resume()
}
For more detail on the other approaches including background and ephemeral sessions, as well as how to handle the NUSRLResponse, see my blogpost.
As you've found out NSURLConnection has been deprecated and NSURLSession is the new shiny.
For your example to work you still need to use the NSURL and the NSURLRequest that you have already created, and then you need an NSURLSession which you can use in various ways.
I can see that you already use the callback so in your case I assume it would be
session.dataTaskWithRequest(request) { (data, response, error) in
//magic goes here
}
and then the important thing to remember is to call resume() on your task.
So...to translate your code I'm thinking something along those lines
func postToServerFunction() {
let url: NSURL = NSURL(string: "http://mytesturl.com")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
//let textfeld = String(UserTextField.text)
let bodyData = "data=" + UserTextField.text!
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
let session = NSURLSession.defaultSession()
let task = session.dataTaskWithRequest(request) { (data, response, error) in
//magic goes here
}
task.resume()
}
You can read more about NSURL session in this tutorial from raywenderlich.com
Hope that helps

NSURLRequest produce different result than HTTP proxy client

I send the same HTTP message from a HTTP proxy client and with NSURLRequest + NSURLConnection, and get back different result. It is an authentication request. From HTTP proxy authentication request is accepted, sending from app not. Why? Accepted means after redirection HTML will contains no Oops substring.
let url = NSURL(string: "http://www.swisshttp.weact.ch/en/user/login")
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let email2 = (viewController!.email.text as NSString).stringByReplacingOccurrencesOfString("#", withString: "%40")
let str = "name=\(email2)&pass=\(viewController!.password.text)&form_id=user_login" as NSString
let d = str.dataUsingEncoding(NSUTF8StringEncoding)
if let d2 = d {
request.HTTPBody = d2
let urlConnection = NSURLConnection(request: request, delegate: self)
}
UPDATE
I have put #teamnorge's code below into playground and into an empty Single View Application project. Returned HTML in project contains the Oops substring, code used in playground not containes it, any idea what is going on, why same request produce different HTML result? I get failed message also from iOS device and from simulator too.
UPDATE
Removed NSURLRequest cache like here recommended, but still not works as expected. And here.
UPDATE
Tried to remove all the credentials like here, but didn't help, no credential was found.
It looks like when you receive HTTP 302 and new Location URL, iOS does automatically fetch the page by this URL, so I guess your response is in fact the HTML content of the redirection page. Please verify.
UPDATE:
import UIKit
import XCPlayground
let url = NSURL(string: "http://www.swisshttp.weact.ch/en/user/login")
let request = NSMutableURLRequest(URL: url!)
let str = "name=kukodajanos%40icloud.com&pass=jelszo&form_id=user_login" as NSString
let d = str.dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = d
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.currentQueue()) { response, maybeData, error in
if let data = maybeData {
let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
println(contents)
if contents!.rangeOfString("Oops").length == 0 {
println("success")
} else {
println("failed")
}
} else {
println(error.localizedDescription)
}
}
XCPSetExecutionShouldContinueIndefinitely()

Swift - how can you build a web based app?

I am creating a web based iOS app.
Simply say, my system is like below.
A user input his name on the app
the app POST it to "destination.php"
"destination.php" stores the received POST to a DB
On the app side, Swift code will be like below.
let strData = parameter.dataUsingEncoding(NSUTF8StringEncoding)
let url = NSURL(string:"http://example.com/destination.php")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.HTTPBody = strData
NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.mainQueue()){(res, data, err) in
//do something
}
I already confirmed that it works well, but from a security point of view, I'm not comfortable with this, because there are no security authorization between the app and "destination.php". In other words, if someone evil finds the URL of "destination.php", he can easily mess up the system with some scripts (posting tons of data to the php, for example).
Is there any good ways to make this kind of connection secure?
Set up Basic authentication on your server and use something like this to build your request.
func request(url: NSURL) -> NSURLRequest {
var request = NSMutableURLRequest(URL: url)
request.setValue(self.authorisation(), forHTTPHeaderField: "Authorization")
request.HTTPMethod = "GET"
return request
}
func authorisation() -> String {
let string = "stuff".stringByAppendingFormat(":%#", "password")
let data = string.dataUsingEncoding(NSASCIIStringEncoding)
let encodedString = data?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding76CharacterLineLength)
let returnValue = "Basic".stringByAppendingFormat(" %#", encodedString!)
return returnValue
}

Resources