How to execute URL requests from an iOS application? - iphone

I want to send the following request to the server. The server already knows what to do with it, but how can I send it?
http://www.********.com/ajax.php?script=logoutUser&username=****

For a synchronous request you would do the following:
NSURL *url = [NSURL URLWithString:#"http://www.********.com/ajax.php?script=logoutUser&username=****"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;
//send it synchronous
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// check for an error. If there is a network error, you should handle it here.
if(!error)
{
//log response
NSLog(#"Response from server = %#", responseString);
}
Update: for doing an asynchronous request please refere to this example

You can do:
NSString *resp = [NSString stringWithContentsOfURL:url usedEncoding:enc error: &error];

Related

Get http response code in ios when using sendSynchronousRequest [duplicate]

This question already has answers here:
how do I check an http request response status code from iOS?
(2 answers)
Closed 9 years ago.
I have a working http GET without using any third party bits, I am new to iOS so this was a struggle to setup initially. My code looks like:
-(NSString *) SendGetRequestToRest:(NSString *)urlEndString
{
NSString *userName = #"userN";
NSString *password = #"PassW";
NSString *urlBaseString = #"http://someurl.co.uk/";
NSString *urlString = [NSString stringWithFormat:#"%#%#", urlBaseString, urlEndString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSString *str1 = [NSString stringWithFormat:#"%#:%#", userName, password];
NSString *encodedString = [self stringByBase64EncodingWithString:str1];
[request addValue:[NSString stringWithFormat:#"Basic %#",encodedString] forHTTPHeaderField:#"Authorization"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"str: %#", str);
return str;
}
What I need to do is track when the status code of the http GET is not a nice 200, I saw How to check status of web server in iOS? and this looks promising i.e. add this:
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
{
if ([response statusCode] == 404)
{
/// do some stuff
}
}
But I cant see how to connect this up to
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
as it doesnt accept a delegate?
You can use returningResponse parameter to get "response":
NSHTTPURLResponse *response = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
if ([response statusCode] == 404)
{
// Do whatever you want to do after getting response
}

Sending Data from UITextField to PHP script via NSURLConnection or JSon

Hi I would like to know how I can go about sending data from 4 UITextField's to a PHP script on a website using NSURLConnection or JSon. Whatever is easier, how can I do this exactly?
Thanks in advance!
Easiest way (synchronous)
NSString strForTextField1 = textField1.text;
NSString strForTextField2 = textField1.text;
NSString strForTextField3 = textField1.text;
NSString strForTextField4 = textField1.text;
//Build the request
NSString *stringOfRequest = [NSString stringWithFormat:#"www.yourserver.com?var1=%#&var2=%#&var3=%#&var4=%#", strForTextField1, strForTextField2, strForTextField3, strForTextField4];
NSURL *url = [NSURL URLWithString:stringOfRequest];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;
//send it synchronous
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
if(!error)
{
//log response
NSLog(#"Response from server = %#", responseString);
}

Google Translate API in Xcode: NSMutableURLRequest returning NULL, not expected result

when I run the following google translation API URL http://translate.google.com/translate_a/t?client=t&text=Hello&langpair=en|fr it returns the correct result.
However, when I try to use the following in Xcode it returns (Null). I would appreciate any help or insight you can provide.
NSString *urlPath = [NSString stringWithFormat:#"/translate_a/t?client=t&text=%#&langpair=en|fr",#"Hello"];
NSURL *url = [[NSURL alloc] initWithScheme:#"http" host:#"translate.google.com" path:urlPath];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"GET"];
NSURLResponse *response;
NSError *error;
NSData *data;
data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Text: %#",result);
Your encoding is incorrect. change it to NSASCIIStringEncoding.
I just fixed your code and ran it locally and it worked like a charm...
here are the results
[[["Bonjour","Hello","",""]],[["interjection",["bonjour","salut","all\u00f4","tiens"]]],"en",,[["Bonjour",[5],1,0,1000,0,1,0]],[["Hello",4,,,""],["Hello",5,[["Bonjour",1000,1,0]],[[0,5]],"Hello"]],,,[],1]

How to post a string to web server url in iphone sdk?

How can I post a string(i.e) a word to web server url in iphone sdk?
Some sample codes or tutorials would be appreciated.
Thanking you.
This may help you, although I havent tested it:
NSMutableString *httpBodyString;
NSURL *url;
NSMutableString *urlString;
httpBodyString=[[NSMutableString alloc] initWithString:#"Name=The Big Bopper&Subject=Hello Baby&MsgBody=...You knooow what I like...Chantilly lace..."];
urlString=[[NSMutableString alloc] initWithString:#"http://www.somedomain.com/contactform.php"];
url=[[NSURL alloc] initWithString:urlString];
[urlString release];
NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url];
[url release];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[httpBodyString dataUsingEncoding:NSISOLatin1StringEncoding]];
[httpBodyString release];
NSURLConnection *connectionResponse = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
if (!connectionResponse)
{
NSLog(#"Failed to submit request");
}
else
{
NSLog(#"--------- Request submitted ---------");
NSLog(#"connection: %# method: %#, encoded body: %#, body: %a", connectionResponse, [urlRequest HTTPMethod], [urlRequest HTTPBody], httpBodyString);
NSLog(#"New connection retain count: %d", [connectionResponse retainCount]);
responseData=[[NSMutableData data] retain];
NSLog(#"response", responseData);
}
Source: http://www.iphonedevsdk.com/forum/iphone-sdk-development/6341-help-executing-http-url-post-variables.html
You can post the string to webservice in so many ways, In those one is
Using Rest protocol:
It has two sub types, HTTP GET, HTTP POST. The Http Get is simple.
You can add the value to the attribute and you can directly call the service.
Check the following code.
NSString *url = #"http://123.456.789.0?action=get_movies";
Here the I am passing the get_movies string to the server to the action attribute.
and then follow the code for requesting to server.
NSURL *reqUrl = [[NSURL alloc] initWithString:url];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:reqUrl];
NSError *error;
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSStringEncoding responseEncoding = NSUTF8StringEncoding;
if ([response textEncodingName]) {
CFStringEncoding cfStringEncoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)[response textEncodingName]);
if (cfStringEncoding != kCFStringEncodingInvalidId) {
responseEncoding = CFStringConvertEncodingToNSStringEncoding(cfStringEncoding);
}
}
[reqUrl release];
NSString *dataString = [[NSString alloc] initWithData:data encoding:responseEncoding];
the dataString is the responseString from the server. You can use that.
Regards,
Satya.

Twitter oauth problem with frindship/create in api

I am using Google Data API sample touch application, which is available at code.google....
I am having a problem can any one help.
Please tell me if I am doing some thing wrong.
The user who has loged in has to follow some person XYZ (just using
XYZ for security purpose).
I am using the URL
urlStr = #"http://api.twitter.com/1/friendships/create/XYZ.xml";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:url];
//made post as requested in twitter API
[request setHTTPMethod:#"POST"];
ConnectAppDelegate *appDelegate = (ConnectAppDelegate *)
[[UIApplication sharedApplication] delegate];
[mAouth authorizeRequest:request];
NSError *error = nil;
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
if (data) {
// API fetch succeeded
NSString *str = [[[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"API response: %#", str);
} else {
// fetch failed
NSLog(#"API fetch error: %#", error);
}
In the response I get
http://api.twitter.com/1/friendships/create/XYZ.xml
2010-06-11 16:04:39.437 Connect[4265:20b] API response:
<?xml
version="1.0" encoding="UTF-8"?>
<hash>
<request>/1/friendships/create/XYZ.xml</request>
<error>Invalid / used nonce</error>
</hash>
This error can happen if your time and the server time are more than 5 mins different, check that your server / pc has the same time as the server.