i have created a HTTP POST request in swift ios. when i fetch a post variables in php file, it is showing blank, i am not getting a variable value. below my swift code, look it.
var dataString = "name=john&type=student"
var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: "http://www.example.com/example.php")
var postString = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postString
var connection = NSURLConnection(request: request, delegate: self, startImmediately: false)
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
//New request so we need to clear the data object
println(response)
}
Php code:
<?php
echo $_POST['name'];
?>
Anyone can suggest what should i do for getting a variables value. Thanks
You should use a Content-Type of application/x-www-form-urlencoded instead of application/json
Related
I want to pass two values in HTTP request body. I try to do it like this but it isn't working. can anyone help me?
guard let url = URL(string: "*****") else { return }
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let post: String = "cardId=\(viewModel.getCardId())&requestId=\(viewModel.getRequestId())"
if let postData: Data = post.data(using: String.Encoding.ascii, allowLossyConversion: true) {
request.httpBody = postData
webView.load(request as URLRequest)
}
I was working on Implementing one third party API with certificate and Authentication. I have put certificate in my resource folder, I also have password for that. For the above think I implement NSURLSession and delegate method "didrecieve challenge" almost working fine. But In response I Only get Header parts not body Please help me what mistack I made. The response from server should be XML format but Got only below parts :
status code: 200, headers {
Connection = close;
"Content-Length" = 23113;
"Content-Type" = "text/html; charset=ISO-8859-1";
Date = "Tue, 28 Jun 2016 05:26:42 GMT";
Server = "Apache/2.2.15 (CentOS)";
} })
Code:
let xmlString = "<?xml version='1.0' encoding='ISO-8859-1'?><TICKETANYWHERE><COUPON VER='1.0'><TEMPLATELIST /></COUPON></TICKETANYWHERE>"
let xmlData = xmlString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let request = NSMutableURLRequest(URL: NSURL(string: "My URL")!)
request.HTTPMethod = "POST"
request.HTTPBody = xmlData
request.addValue("text/html; charset=ISO-8859-1", forHTTPHeaderField: "Content-Type")
request.setValue("Apache/2.2.15 (CentOS)", forHTTPHeaderField: "Server")
request.addValue("23113", forHTTPHeaderField: "Content-Length")
struct SessionProperties {
static let identifier : String! = "url_session_background_download"
}
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
request.timeoutInterval = 20.0 //(number as! NSTimeInterval)
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let task = session.dataTaskWithRequest(request) { data, response, error in
**print(response)** // Got Only Header Part Not Body
}
task.resume()
An NSHTTPURLResponse object is not supposed to contain data. It contains only the metadata (headers, etc.). The body data is in the data object.
Can anybody help on connecting issue swift ios with soap object
var soapMessage = "<?xml version='1.0' encoding='UTF-8'?><soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'><soap:Body> <BindCategory xmlns=‘http://tempuri.org/'></BindCategory></soap:Body></soap:Envelope>"
var urlString = "http://assetwebservice.sudesi.in/service.svc"
var msgLength = String(count(soapMessage))
var url = NSURL(string: urlString)!
var theRequest = NSMutableURLRequest(URL: url)
theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
theRequest.addValue("http://tempuri.org/IService/BindCategory", forHTTPHeaderField: "Soapaction")
theRequest.addValue(msgLength, forHTTPHeaderField: "Content-Length")
theRequest.HTTPMethod = "POST"
theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
var connection = NSURLConnection(request: theRequest, delegate: self,startImmediately: true)
connection?.start()
if (connection == true) {
println("Connection success")
var mutableData : Void = NSMutableData.initialize()
}else{
println("Error in connection")
}
Well, the thing that jumps out at me is the following:
if (connection == true) {
println("Connection success")
// What does this line mean? I can't make sense of it.
var mutableData : Void = NSMutableData.initialize()
}
You are comparing an NSURLConnection? to a Bool. This is never going to be true. Besides, this is not the correct way to determine whether a connection is successful. NSURLConnection has an optional initializer so that it can check whether its parameters are valid, not so that the success of a connection can be determined. Success will be determined by the appropriate callbacks to the delegate.
You should look into using NSURLSession instead of NSURLConnection unless you have to support iOS < 7.0, which I doubt. I have a suspicion—perhaps false—that the questioner is a C# programmer doing Swift who is perhaps not familiar with the delegate pattern, which is common in Apple's frameworks but not common at all in Microsoft's. If so, NSURLSession's interface will be much more palatable.
Issue is in soap envevlope mapping , now I have correct that , all things are now perfect.
Thanks
I figured it out solution at the bottom
I am trying to make an HTTP post request to my server. Here's what I did
var request : NSMutableURLRequest = NSMutableURLRequest(URL : NSURL(string : "myURL")
let session : NSURLSession = NSURLSession.sharedSession()
request.allHTTPHeaderFields = (headers as [NSObject : AnyObject])
request.HTTPShouldHandleCookies = true
request.HTTPMethod = "POST"
var postData = "frontend=iOS"
request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
NSHTTPCookieStorage.sharedHTTPCookieStorage().cookieAcceptPolicy = NSHTTPCookieAcceptPolicy.Always
println(request.allHTTPHeaderFields)
println(request.HTTPBody)
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
let json:JSON = JSON(data: data)
println(json)
onCompletion(json, error)
})
task.resume()
this is not setting the HTTPRequest.POST
I tried printing the request to the server on the server side. IT said post was empty
POST : [QueryDict : {}]
What am I missing here? Any help is appreciated
Solution :
I mistakenly set the content-value to application/json when in fact it
was not a json body. Removing it solved the problem
use https://github.com/Alamofire/Alamofire
easy networking :)
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
.response { (request, response, data, error) in
println(request)
println(response)
println(error)
}
you can use all of the below.
public enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
Heres the method I used in my logging library: https://github.com/goktugyil/QorumLogs
var url = NSURL(string: urlstring)
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding)
var connection = NSURLConnection(request: request, delegate: nil, startImmediately: true)
See How to escape the HTTP params in Swift on the way to correctly encode key-value pairs into the data string.
So I'm trying to do an async POST request to my server from my iOS device.
Here's the Swift code I've written:
var urlString = "https://eamorr.com/ajax/login.php"
var url = NSURL(string: urlString)
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
var params = ["uname":"Eamorr", "pword":"mySecret"] as Dictionary<String, String>
request.HTTPBody = params. //what to do here???
var connection = NSURLConnection(request: request, delegate: self, startImmediately: true)
The problem is, how do (reliably) convert the params to a POST string? (My server is expecting plain old POST parameters... Nothing fancy - no JSON, etc.)
I need this to be very reliable (i.e. not a hack), so I'd prefer if there was some base class (written by Apple) that I could use.
Does anyone have any ideas?
Some of what bbarnhart suggests, but to actually create the body data, use:
let body = "&".join(map(params, {
let key = $0.0.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let value = $0.1.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
return "\(key!)=\(value!)"
}))
request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)
Basically escape and convert each item into "key=value" and then string them all together separated by "&"
You'll also (probably) need to set the Content-Type header as recommended by bbarnhart:
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
To configure your post you need to do three things.
Set Content-Type to application/x-www-form-urlencoded
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
Set the body as a key/value delimited by ampersand string and convert to NSData:
let myPostBody = "uname=Eamorr&pword=mySecret"
request.HTTPBoddy = (myPostBody as NSString).dataUsingEncoding(NSUTF8StringEncoding)
Set the Content-Length:
request.addValue(String(myPostBody.length), forHTTPHeaderField: "Content-Length")