xml post as parameter for Objective C - objective-c

How does one post xml as parameter with Objective C?
I've sent a username and a password in xml to the server. I've tried using ASIFormDataRequest. I've posted xml and the server've given the error that is "username or password is false". I think the server doesn't parse the posting xml. Is there any way to post xml as parameter?
NSURL *url = [NSURL URLWithString:#"url code"];
ASIFormDataRequest *request1 =[ASIFormDataRequest requestWithURL:url];
[request1 setPostValue:"xml block" forKey:#"data"];
[request1 addRequestHeader:#"Content-Type" value:#"application/xml;"];
[request1 setDelegate:self];
[request1 startSynchronous];

Yes, it is. Look at my example:
NSString *message = [[NSString alloc] initWithFormat:#"<?xml version=\"1.0\" ?>\n<parameters></parameters>"];
url = [NSURL URLWithString:#"https://https_url.com"];
request = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d",[message length]];
[request addValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[message dataUsingEncoding:NSUTF8StringEncoding]];
[message release];

Related

Can't obtain a response from WCF service

i have a trouble when i try to call a web service made in WCF, this service is calling by Mac os x app.
this is the code
soapMessage = #"{name:\"Sergio\"}";
NSURL *url = [NSURL URLWithString:#"http://localhost/GSBonoServicios/GSBonoService.svc/HelloWorld"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest setHTTPMethod: #"POST"];
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSData *requestData = [NSData dataWithBytes:[soapMessage UTF8String] length:[soapMessage length]];
[theRequest setHTTPBody:requestData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
The connection is successful but didn't a response, i try implementing some tutorials and I'm looking in Stackoverflow and i find many answers but nothing works, i hope you can help me.
ps. I do not speak much English, but I hope I explained, Thanks
Finally I found the solution the problem was in the service, and the code that works is
NSString *name=#"Sergio";
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys: name, #"name",
nil];
NSURL *url = [NSURL URLWithString:#"http://www.myserver.com/Servicio/ServicioEjemplo.svc/HelloWorld"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod: #"POST"];
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[theRequest setValue:#"applicat ion/json" forHTTPHeaderField:#"Content-Type"];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:kNilOptions error:&error];
[theRequest setHTTPBody:postdata];
NSLog(#"JSON summary: %#", [[NSString alloc] initWithData:postdata
encoding:NSUTF8StringEncoding]);
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
Thanks

sending data using CURL in objective c [duplicate]

This question already has answers here:
Tutorials for using HTTP POST and GET on the iPhone in Objective-C [closed]
(5 answers)
Closed 9 years ago.
how i have to use the following CURL command in objective c,
curl -d lang=fr -d badge=0 http://www.redis.com/subscriber/J8lHY4X1XkU
Thanks in advance
You could try:
NSURL *url = [NSURL URLWithString:#"http://www.redis.com/subscriber/J8lHY4X1XkU"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString* str = #"lang=fr&badge=0";
NSData* body = [str dataUsingEncoding:NSUTF8StringEncoding];
[req setHTTPMethod:#"POST"];
[req setHTTPBody:body];
[req setValue:[NSString stringWithFormat:#"%d", [str length]] forHTTPHeaderField:#"Content-length"];
[[NSURLConnection alloc] initWithRequest:req delegate:self];
More about this you can find on iOS documentation: NSURLConnection and NSMutableURLRequest
Can you try following code?
NSURL *url = [NSURL URLWithString:#"http://www.redis.com/subscriber/J8lHY4X1XkU?lang=fr&badge=0"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:120];
[request setURL:url];
[request setHTTPMethod:#"GET"];
NSData *responce = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];

Post data in Objective C using Json

I am trying to post data to a PHP web service.
I am familiar doing this in html using query $.post but I am very much stumped trying this in objective C.
I tried several blogs & questions found on stackoverflow.
I finally came up with the following code:
NSString *jsonRequest = [NSString stringWithFormat:#"{\"Email\":\"%#\",\"FirstName\":\"%#\"}",user,fname];
NSLog(#"Request: %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"http:myurl..."];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
I also tried:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
My web service creates a new user on post and returns the userID.
Both successfully make the web service call(a new userID is created), however they do not post the data, i.e. a blank user is created every time.
Please tell me if I am missing anything.
Thanks.
My other attempts:
NSMutableURLRequest *request =
[[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:#"myUrl.. "]];
[request setHTTPMethod:#"POST"];
NSString *postString = #"Email=me#test.com&FirstName=Test";
[request setValue:[NSString
stringWithFormat:#"%d", [postString length]]
forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString
dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc]
initWithRequest:request delegate:self];
I finally solved the issue:
FInally, figured out what was wrong. I was using http://mypath?params=123 as my url. I did not gig the complete url(never needed it in other languages). But here I needed to give htt://mypath/index.php?params=123
I think you would be better off using the NSJSONSerialization class like this:
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
email, #"Email",
fname, #"FirstName",
nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
[request setHTTPBody:postData];
Using a dictionary and then converting it to JSON it's easier than creating it like a string.
Good luck!
[SWIFT 3.0] (update)
let tmp = ["email": email,
"FirstName": fname]
let postData = try? JSONSerialization.data(withJSONObject: tmp, options: .prettyPrinted)
request.httpBody = postData
I have run your code, and server side receive all message.
POST / HTTP/1.1
Host: linux-test
User-Agent: demoTest/1.0 CFNetwork/548.1.4 Darwin/11.3.0
Content-Length: 44
Accept: application/json
Content-Type: application/json
Accept-Language: en
Accept-Encoding: gzip, deflate
Connection: keep-alive
{"Email":"test#test.com","FirstName":"test"}
And follow code, if jsonRequest has Non-ASCII characters, the [jsonRequest length] will be wrong.
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
You can use strlen instead.
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:strlen([jsonRequest UTF8String])];
or
[jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
Try this one
NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#posts", SeverURL]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request addRequestHeader:#"content-type" value:#"application/json"];
[request addRequestHeader:#"User-Agent" value:#"iOS"];
request.allowCompressedResponse = NO;
request.useCookiePersistence = NO;
request.shouldCompressRequestBody = NO;
request.delegate=self;
NSString *json=[[self prepareData] JSONRepresentation];//SBJSON lib, convert a dict to json string
[request appendPostData:[NSMutableData dataWithData:[json dataUsingEncoding:NSUTF8StringEncoding]]];
[request startSynchronous];

NSMutableURLRequest with "=" char in parameters

I have to post parameters to an url and i have a parameter that has a "=" char so I should escape it. Here attach what I'm doing in objective-C.
for (NSString* key in json) {
NSString *current = [NSString stringWithFormat:#"&%#=%#",key,[json objectForKey:key]];
[post appendString: current];
}
//so post has this style: "&password=eodhxgkpo=&usuario=user1"
NSURL *urlObj = [NSURL URLWithString: itemAddress];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: urlObj];
NSData *requestData = [NSData dataWithBytes:[post UTF8String] length:[post length]];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
[webView loadRequest: request];
this same code works if password has no "=" char. So there is any way to escape this kind of chars?
(the content-type has to be "application/x-www-form-urlencoded")
Thanks for your help
Danilo
You have the list of escapes codes for URL here:
http://www.december.com/html/spec/esccodes.html
You have to use %3D for escaping =
Hope it helps!
Try something like
// path is a NSString
NSURL* url = [NSURL URLWithString:[path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

POST to server results in GET request

I'm trying to do a simple POST request to a server, with this code:
NSString *post = [[NSString alloc] initWithFormat:#"email=%#&password=%#", self.email.text, ..]; // .. simplified keychainItem
NSData *postEncoded = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [postEncoded length]];
NSURL *url = [NSURL URLWithString:#"http://eng.studev.groept.be/web2.0/a11_web02/testApp.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postEncoded];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
When debugging on the server, this actually results in a GET request. That explains why I'm getting a PHP error when trying to read $_POST[ ] variables. Bottom line: why isn't the setHTTPMethod: being accepted?
(extra information: when just coding in PHP on the server, use of POST works normally)