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.
Related
In iOS 9, I'm using NSURLSession and for one specific URL, it's generating the following error:
Error Domain=NSPOSIXErrorDomain Code=89 "Operation canceled".
Configuring ATS diagnostic, using nscurl --ats-diagnostics for current url returns a nil error.
Anyone else seen this kind?
Update:
now give response:
"curl --head soap.alfabank.kz:30444/soa/rate?wsdl"
HTTP/1.1 405 Method Not Allowed Content-Type: application/soap+xml;
charset=UTF-8 Content-Length: 286
Server: Jetty(8.1.14.v20131031)
Strict-Transport-Security: max-age=157680000
X-FRAME-OPTIONS: DENY
Some code:
let url = "https://soap.alfabank.kz:30444/soa/rate?wsdl"
let soapMessage = "<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\"><s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><GetRates xmlns=\"http://soa.rate.alfabank.kz/\"><RateListRq reqid=\"6f56631b-01d0-4886-917b-1c5565743627\" systemcode=\"VSTest\"><list_type xmlns=\"\">short</list_type><period xmlns=\"\"><fromDate>2016-09-07</fromDate><toDate>2016-09-07</toDate></period></RateListRq></GetRates></s:Body></s:Envelope>"
let request = NSMutableURLRequest(URL: NSURL(string:url)!)
let msgLength = soapMessage.characters.count
request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue(String(msgLength), forHTTPHeaderField: "Content-Length")
request.HTTPMethod = "POST"
request.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let task = session.dataTaskWithRequest(request){
data, response, error in
if error != nil {
print(error)
}
else {
//some
}
}
task.resume()
Remove the space after the semicolon in the Content-Type header. Apparently NSURLSession is very picky about validating that header (because a curl request succeeded without making that change).
And remove the Content-Length header as previously noted.
Here is my prepareForSegue method
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let vc = segue.destinationViewController as! AllCommentsViewController
if segue.identifier == "addComment" {
if let stringText = commentTF.text {
vc.CommentsArray.append(stringText)
let urlString = "http://sekaaleksic.cloudlk.com/api/v1/post/comment/\(postId)/submitComment"
let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
let session = NSURLSession.sharedSession()
let params = ["comment=\(stringText)"]
request.HTTPBody = try? NSJSONSerialization.dataWithJSONObject(params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("\(stringText)", forHTTPHeaderField: "comment")
request.HTTPMethod = "POST"
let task = session.dataTaskWithRequest(request, completionHandler: { data, response, error -> Void in
print(request.HTTPBody)
print(params)
print(error)
print(response)
print(data)
})
task.resume()
}
}
}
}
So, what's the problem?
As you see, my urlString is where Wordpress API for submitting a comment. postId is an ID of a post.
I should do something like this: $_POST['comment'] = 'some comment message';
But this code isn't working (you can check the number of Comments for specific post on [this link][1])
Here is the XCode Log ->
["test"]
Optional(<5b22636f 6d6d656e 743d7465 7374225d>)
["comment=test"]
nil
Optional(<NSHTTPURLResponse: 0x137bd1300> { URL: http://sekaaleksic.cloudlk.com/api/v1/post/comment/1/submitComment } { status code: 200, headers {
"Cache-Control" = "no-cache, must-revalidate, max-age=0, no-cache";
Connection = "Keep-Alive";
"Content-Encoding" = gzip;
"Content-Length" = 70;
"Content-Type" = "application/json";
Date = "Wed, 10 Feb 2016 14:00:03 GMT";
Expires = "Wed, 11 Jan 1984 05:00:00 GMT";
"Keep-Alive" = "timeout=5, max=700";
Pragma = "no-cache";
Server = Apache;
Vary = "Accept-Encoding";
} })
Optional(<7b227374 61747573 223a6661 6c73652c 22657870 6c61696e 223a2243 6f6d6d65 6e742070 6f737420 69732065 6d707479 227d>)
[1]: http://sekaaleksic.cloudlk.com/api/v1/post/1/countComments
You are encoding the JSON wrong.
Make params equal to:
["comment": stringText]
JSON is used to encode dictionaries, not concatenated strings.
let urlString = "https://192.168.1.167:8090/Attendance/register"
let url = NSURL(string: urlString)
let theRequest = NSMutableURLRequest(URL: url!)
theRequest.HTTPMethod = "POST"
let parameters = ["firsrtName": regFirstNameTxtField.text!, "lastName": regLastNameTxtField.text!,"email": regEmailTxtField.text!,"password": regPassWordTxtField.text!,"phone": regPhoneNoTxtField.text!] as Dictionary<String, String>
var err: NSError?
do {
theRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: [])
} catch let error as NSError {
err = error
theRequest.HTTPBody = nil
} // pass dictionary to nsdata object and set it as request body
theRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
theRequest.addValue("application/json", forHTTPHeaderField: "Accept")
var connectRequest = NSURLConnection(request: theRequest, delegate: self)
I am unable to post a request in swift. It worked perfectly with my older version of xcode. But now when I run it shows the following error message : UserInfo={NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made.,
SErrorFailingURLKey=https://192.168.1.167:8090/Attendance/register}
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()
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