send post request with dynamic data - objective-c

good afternoon
I have been looking but I haven't found anything similar
I am starting with Xcode and objective C please you be patient with me
I want do this
I have a text field intended to be a search box
currently I send a POST request programmatically and the parameters are static
well, I want dynamic parameters
the content of the text field is dynamic parameters
how do I can do it?
I have also a button for sending the request
help please
this is code of the request
NSString *Post = [[NSString alloc] initWithFormat:#"query=deporte"];
NSURL *Url = [NSURL URLWithString:#"http://www.laleo.com/ebooks_android/ebooks_search_json.php"];
NSData *PostData = [Post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [PostData length]];
NSMutableURLRequest *Request = [[NSMutableURLRequest alloc] init];
[Request setURL:Url];
[Request setHTTPMethod:#"POST"];
[Request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[Request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[Request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[Request setHTTPBody:PostData];
NSData *returnData = [NSURLConnection sendSynchronousRequest:Request returningResponse:nil error:nil];
//NSString *myString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSError *error;
NSMutableDictionary *allCourses = [NSJSONSerialization
JSONObjectWithData:returnData
options:NSJSONReadingMutableContainers
error:&error];
The text field already is available through of #synthesize palabra;
The button is in the graphical interface

First of all, you should create an action handler for your button. Use Interface Builder for that. Also you'll need to connect the outlet for the textfield with your viewcontroller's class. Then, just take a text value from your textfield and send it into the request. If you need to know how you can receive a text from the textfield, just use this:
NSString *text = _textField.text;

Related

post request to server does not send the content of textfields?

I'm trying to send the content of my textfields firstname and lastname with my button sendpost to my php server. Once I run my app and fill my textfields with some random text and press send, I receive an e-mail on my server but there is no content.
(void) sendAction{
NSError *error = nil;
NSString *postparams = [NSString stringWithFormat:#"info=%#_%#",firstname.text,lastname.text];
NSData * postdata = [postparams dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString * postlength= [NSString stringWithFormat:#"%d",[postdata length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"http://faketest.com/test/mail.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postlength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postdata];
NSData * rawdata = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSString *rawdatastring =[[NSString alloc]initWithData:rawdata encoding:NSUTF8StringEncoding];
NSLog(#"%#",rawdatastring);
}
I believe it may be because you're using a "Current-Type" header, instead of the usual "Content-Type" header. Try the following and see if it solves the problem:
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];

NSMutableURLRequest returns old values even cachePolicy is NSURLCacheStorageNotAllowed

Im using codes posted here:
connection release method in connectionDidFinishLoading, causes error
now first execute returns didFail log.
second execute; returns old response data.
albeit my (localhost) server is totally offline.
and cachePolicy is NSURLCacheStorageNotAllowed (check the code on the link I posted above)
NSMutableURLRequest *request=
[NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:3.0f];
the response data seems cached somewhere and still exists.
but if I use NSURLRequestReloadIgnoringLocalAndRemoteCacheData //which is commented as -not implemented-
not returns old cache.
but if so what is the difference between:
NSURLRequestReloadIgnoringLocalAndRemoteCacheData
and
NSURLCacheStorageNotAllowed
what shall I do ?
NSURLCacheStorageNotAllowed refers to NSCachedURLResponse and is an value of enum NSURLCacheStoragePolicy. Since the cache policy of NSMutableURLRequest is also an enum (NSURLRequestCachePolicy) you just pass wrong int to the static method creating NSMutableURLRequest. In this case NSURLCacheStorageNotAllowed is just 2 which equals to NSURLRequestReturnCacheDataElseLoad - and that is why you get old data.
Try This
NSString *Post = [[NSString alloc] initWithFormat:#"Post Parameters"];
NSURL *Url = [NSURL URLWithString:#"Url"];
NSData *PostData = [Post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [PostData length]];
NSMutableURLRequest *Request = [[NSMutableURLRequest alloc] init];
[Request setURL:Url];
[Request setHTTPMethod:#"POST"];
[Request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[Request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[Request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[Request setHTTPBody:PostData];
NSError *error;
NSURLResponse *response;
NSData *Result = [NSURLConnection sendSynchronousRequest:Request returningResponse:&response error:&error];
if (!Result)
{
NSLog(#"Error");
}
else
{
//Parse the result
}

cocoa http post request

hello i know this has been asked and answered many times but i cant seem to understand how it works (im new to iphone dev & objective c in general)
i am trying to make a create user for my app. i have a file create.php on my server that expects to get a _POST variable called id. after it is called it echos "DONE" for success and "EXIT" for failure.
i found some code and altered it (to the best of my knowledge) to fit my needs :
NSMutableString *tmpurl = [NSMutableString stringWithString: #"http://mysite.com/"];
[tmpurl appendString:#"create.php"];
NSURL *url = [NSURL URLWithString:tmpurl];
NSString *uid = #"32478907348920437829078902347804930893741"; // should chenge for randome.
NSString *post = [NSString stringWithFormat:#"id=%#", uid];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
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:postData];
now i don't know how to see what the page echos back or even if it has reached it.
any information would be appreciated and thank you in advance.
You are missing the NSURLConnection. Depending if you want to send this request synchronous or async, you may need to implement the NSURLConnectionDelegate methods.

iOS http post response to NSDictionary or NSArray

I'm making a HTTP Post and I would like to know how to convert the response to NSDictionary, or NSArray. Here's my code:
NSString *post = [NSString stringWithFormat: #"SomeData=text", text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"https://www.my.site/receiver"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
EDIT:
The response looks like this after converting like this:
NSString *string = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
2011-12-04 11:50:00.924 Dancing Ruby[404:207] response: SID=DQAAAMAAAAAjy9MXrxh7Hi4nXTpyVTnqMR4c_W2wCQmLmO7xDHz7v91kl16tH-0UyazONU2nGjsUYxGzAPd9lvNcCGLfcz7YFLQRhG8yW8_wn3V46g8SY0A5bnfmGhuIbAMoCetow09cOnE7aYUzEZ4u5zVnJFoNepa9BlheFAA8JFLomw3luHedLkJZi_CQJO48CtwLZeIF9zhD5RNUDUretNh_1QBN2fHntSiqASMHHHyd9dtlTaXpokx_KIJovxo0dNYUJbs
LSID=DQAAAMIAAACgjuwUzSRNh2xXrWsdA81_fLVCguvatiHHU6b1dMm0TD6-lQyl-odfIfLGWgee4_j3HXUNsqtTm-aEFgylW2QURA5F9_1Fx8WRECIWOkUoLfWBGchoxRfhxKqCoD-zzgg1opjSmrDyv0U1NZRN7YGiqkLj4Fz_Qm6oPapov2_J33KT0ENFTKnqyzS0zU3wHgKSGb1aoKKO0ZJCTFk20AX3cLYPuMWoJcnyrLipCzZjkjwGEEhfgz31ISPS9OGezPzYJji-UxTmaJB7Va7SGquX
Auth=DQAAAMEAAACgjuwUzSRNh2xXrWsdA81_fLVCguvatiHHU6b1dMm0TD6-lQyl-odfIfLGWgee4_gex6ZHpCOn0tXFwuivD7ESwhFMJGdLRYSspk-leGqj-eCkXUgsg4DBvxPbdpREFlU_j0RGm_qufXlaScZV3x17plY5-xrhvhziEVFf3eLiHEmN9HHNwh8uElyYyJ1rLNAbIunpG3D10ASr4WPQDIz_52OOKy07CmQrBNDdUcpkT5bXqBe3Cdw8aqld0LZH2AIMEdj7PupfRaneJgF-nCBZ
You need to use some kind of parser for that. If the response is in XML you could use NSXMLParser. Here you can find a tutorial on how to use it. The same concept applies for any other kind of data. You have to know beforehand what to expect so you can parse it properly.
I hope it helps

Put JSON encoded array as NSData from NSURLResponse into NSArray

I'm unable to get this to work:
NSString *post = [NSString stringWithFormat:#"userudid=%#", [udid stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"%#",post);
NSData *postData = [NSData dataWithBytes:[post UTF8String] length:[post length]];
//[udid dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSLog(#"%#",postData);
//NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.myserver.com/myapp/readtags2.php"]];
[request setURL:url];
[request setHTTPMethod:#"POST"];
//[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
NSString *content = [NSString stringWithUTF8String:[urlData bytes]];
NSLog(#"responseData: %#", content);
is the POST formed correctly? Because i can get it to work from a manual html form posting to the same php file, but i get nothing back when doing it from iOS
You might have an easier time doing HTTP POST's with ASIHTTPRequest.
Form-Posting with ASIHTTPRequest is explained in the section titled "Sending a form POST with ASIFormDataRequest" here: http://allseeing-i.com/ASIHTTPRequest/How-to-use
Otherwise, have a look at the NSURLResponse, check the response code and see if iOS thinks the POST was successful.
Other thing you can use to check is a tool like wireshark to compare the network traffic from your web-based form POST to the traffic from your iOS POST. It looks like you're doing it right, but the best way to be sure is something like wireshark.