POST request doesn't work - ios

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.

Related

using POST API in ios using URLSession

I'm learning IOS right now and I completely wrote same code with the tutorial. But I got an error like this
"2019-05-29 14:01:25.974883+0900 URLSessionJSONRequests[18165:938499]
Task <0EC532CF-8CA6-42C9-9BD8-6D6E74BB9C06>.<10> finished with error -
code: -1002"
My Code is this.
#IBAction func onPostTab(_ sender: UIButton) {
let parameters = ["id":"uuzaza#naver.com","pw":"1q2w3e4r"]
guard let url = URL(string:"https//taky.co.kr/login/app_login") else{return}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: [])else{
return}
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [] )
print(json)
}catch{
print(error)
}
}
}.resume()
}
what is error code -1002?? I used placeholder API and it is still supported and I think the server is not the problem. Any reference or advice would be grateful!
Kindly check URL first you missed ':' after https.
Just replace your API End-point
https//taky.co.kr/login/app_login
With
https://taky.co.kr/login/app_login
After doing the above changes everything works fine.
API Response:
<NSHTTPURLResponse: 0x60000327d120> { URL: https://taky.co.kr/login/app_login } { Status Code: 200, Headers {
"Cache-Control" = (
"no-store, no-cache, must-revalidate"
);
Connection = (
"Keep-Alive"
);
"Content-Encoding" = (
gzip
);
"Content-Length" = (
93
);
"Content-Type" = (
"text/html; charset=UTF-8"
);
Date = (
"Wed, 29 May 2019 05:32:58 GMT"
);
Expires = (
"Thu, 19 Nov 1981 08:52:00 GMT"
);
"Keep-Alive" = (
"timeout=5, max=100"
);
Pragma = (
"no-cache"
);
Server = (
"Apache/2.4.18 (Ubuntu)"
);
"Set-Cookie" = (
"cookie=9f73o1c13mggukb15fq25usfpc6ms6cp; expires=Wed, 29-May-2019 09:32:58 GMT; Max-Age=14400; path=/; HttpOnly"
);
Vary = (
"Accept-Encoding"
);
} }
{
code = E01;
message = "\Uc544\Uc774\Ub514\Ub97c \Uc785\Ub825\Ud574 \Uc8fc\Uc138\Uc694.";
}

POST request doesn't include params \ JSON

I've setup the api post request which is working fine with postman, however in my swift code it doesn't send the params with the request.
let parameters = ["spotId" : spotId,
"voteruptime" : currentDate,
"voterupid" : userId] as [String : Any]
guard let url = URL(string: "http://example.com:3000/upvote") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("Application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }
request.httpBody = httpBody
print(request.httpBody)
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}
}.resume()
I got a response
<NSHTTPURLResponse: 0x618000a26560> { URL: http://example.com:3000/upvote } { status code: 200, headers {
Connection = "keep-alive";
"Content-Length" = 28;
"Content-Type" = "application/json; charset=utf-8";
Date = "Sat, 21 Oct 2017 03:11:46 GMT";
Etag = "W/\"1c-BWaocQVSSeKjLiaYjOC8+MGSQnc\"";
"X-Powered-By" = Express;} }
{
n = 0;
nModified = 0;
ok = 1;
}
The server code Node JS is:
app.post('/upvote', function(req, res){
Spots.update({_id: req.query.spotId},{$push:{'upvotes':{'voterupid':req.query.voterupid,'voteruptime':req.query.voteruptime}}},function( err, Spots){
console.log(req.url)
if(err){
throw err;
}
res.json(Spots);
});
});
I tried also alamofire, and it's the same issue, no params sent to the server.
I believe the issue is that req.query accesses data passed on the query string, whereas you are POSTing the data in the body of the request.
To access the body, you need to use body-parser as described in multiple answers here: How to access the request body when POSTing using Node.js and Express?

JSON POST parsing issue in swift 3

I am trying to post data suing POST request, but whenever i am posting data I am getting Bad Request error.
Please check this code and if there any issue please let me know,
func callDataCall()
{
let requestURL: NSURL = NSURL(string: "REQUEST_URL")!
//convert MID dict to jsondata
let NewJSONData = try! JSONSerialization.data(withJSONObject: ["Disease_request":["Mid":self.MedicationID]], options: [])
// Convert jsondata to string
let NewJSONDataString = NSString(data:NewJSONData, encoding:String.Encoding.utf8.rawValue) as! String
print("Created Dictionary is : \(NewJSONDataString)")
let urlRequest = NSMutableURLRequest(url: requestURL as URL)
// set up the session
urlRequest.httpMethod = "POST"
urlRequest.httpBody = NewJSONDataString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: urlRequest as URLRequest)
{
data, response, error in
let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode
print("status code is :\(httpResponse)")
if (statusCode == 200 || statusCode == 201)
{
do
{
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: AnyObject]
if let content = json?["Disease"] as? [[String: AnyObject]]
{
for i in 0..<content.count
{
self.medicationContent.append(content[i] as AnyObject)
}
DispatchQueue.main.async(execute: {
self.tableview_Medication.reloadData()
})
}
}
catch
{
print("Error with Json: \(error)")
}
self.stopIndicator()
}
}
task.resume()
}
Response is :
<NSHTTPURLResponse: 0x608000231e40> { URL: "REQUEST_URL" } { status code: 400, headers {
"Cache-Control" = "no-cache";
"Content-Length" = 46;
"Content-Type" = "application/json; charset=utf-8";
Date = "Wed, 30 Nov 2016 10:38:24 GMT";
Expires = "-1";
Pragma = "no-cache";
Server = "Microsoft-IIS/8.5";
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";
"X-Powered-By-Plesk" = PleskWin;
} }
I am using the same logic for Objective C, its working fine for me.
Got the solution !!
The Swift code is fine, i need to add one more line after httpMethod
So now the code as like this
urlRequest.httpMethod = "POST"
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")

How to call HTTPS URL with certificate Authentication

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.

error while requesting json in SWIFT + ios

I am requesting some data by json , I am new to SWIFT for iOS so I don't get whats the problem in my code :
var URL="http://X.X.X.X.X/Api/UserManagement/getMobileUser";
var UserId=uname.text;
var pword=passwd.text;
var PostData: NSString = "{\"data\":{},\"action\":\"System\",\"method\":\"getMobileUser\",\"username\":\" mpc01\",\"password\":\"mpc01\",\"type\":\"rpc\",\"tid\":\"144\"}"
let request = NSMutableURLRequest(URL: NSURL(string: URL)!)
request.HTTPMethod = "POST"
let postString = PostData
//var st:NSData = PostData.dataUsingEncoding(NSUTF8StringEncoding)!
// request.HTTPBody = PostData.dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = (postString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
//let data = (postString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
println("error=\(error)")
return
}
println("response = \(response)")
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString = \(responseString)")
}
task.resume()
THE response I get is :
response = { URL: http://X.X.X.X/Api/UserManagement/getMobileUser } { status code: 500, headers {
"Cache-Control" = "no-cache";
"Content-Length" = 36;
"Content-Type" = "application/json; charset=utf-8";
Date = "Sat, 03 Jan 2015 06:11:51 GMT";
Expires = "-1";
Pragma = "no-cache";
Server = "Microsoft-IIS/7.5";
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";
} }
responseString = Optional({"Message":"An error has occurred."})
I had a similar problem trying to POST to MailGun for some automated emails I was implementing in an app.
I was able to get this working properly with a large HTTP response. I put the full path into Keys.plist so that I can upload my code to github and broke out some of the arguments into variables so I can have them programmatically set later down the road.
// Email the FBO with desired information
// Parse our Keys.plist so we can use our path
var keys: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("Keys", ofType: "plist") {
keys = NSDictionary(contentsOfFile: path)
}
if let dict = keys {
// variablize our https path with API key, recipient and message text
let mailgunAPIPath = dict["mailgunAPIPath"] as? String
let emailRecipient = "bar#foo.com"
let emailMessage = "Testing%20email%20sender%20variables"
// Create a session and fill it with our request
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: mailgunAPIPath! + "from=FBOGo%20Reservation%20%3Cscheduler#<my domain>.com%3E&to=reservations#<my domain>.com&to=\(emailRecipient)&subject=A%20New%20Reservation%21&text=\(emailMessage)")!)
// POST and report back with any errors and response codes
request.HTTPMethod = "POST"
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
print("url = \(response.URL!)")
print("response = \(response)")
let httpResponse = response as! NSHTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
The Mailgun Path is in Keys.plist as a string called mailgunAPIPath with the value:
https://API:key-<my key>#api.mailgun.net/v3/<my domain>.com/messages?
Hope this helps!

Resources