Issue with HTTP request in Objective C - iphone

Iam trying to submit values to an external DB using http request
My code is below
NSString *post =[NSString stringWithFormat:#"user=%#&child=%#&content=%#",userId,childId, crackContent.text];
responseData = [[NSMutableData data] retain];
NSString *hostStr = #"http://myhost.com/addItem.php?";
post = [utilityObj getEncodedUrl:post];
hostStr = [hostStr stringByAppendingString:post];
NSLog(hostStr);
NSLog(hostStr);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:hostStr]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
My issue is that if any space contains any of the parameter it will not submitted, otherwise it is successfully submitted.
Help is highly appreciated.

You may get the parameter encoded before send.
NSString* escapedUrlString =
[unescapedString stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding];
Alternative
NSString * escapedUrlString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)unescapedString,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
kCFStringEncodingUTF8 );

Related

URL Connection: What is the difference between the following?

I need to know the difference between the following two methods of url connection?
What is the significance of these two methods?
Which method is preferred in what circumstances?
Method 1:
file.h
#import
#define kPostURL #"http://localhost/php/register.php"
#define kemail #"email"
#define kpassword #"password"
#interface signup : UIViewController
{
...
...
NSURLConnection *postConnection;
}
#property ...
...
#end
file.m
NSMutableDictionary *input=[[NSMutableDictionary alloc]init];
...
...
...
NSMutableString *postString = [NSMutableString stringWithString:kPostURL];
[postString appendString: [NSString stringWithFormat:#"?%#=%#", kemail, [input objectForKey:#"email"] ]];
[postString appendString: [NSString stringWithFormat:#"&%#=%#", kpassword, [input objectForKey:#"password"] ]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:postString]];
[request setHTTPMethod:#"POST"];
postConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
NSLog(#"postconnection: %#", postConnection);
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: postString ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(#"serverOutput = %#", serverOutput);
Method 2:
NSString *post =[NSString stringWithFormat:#"email=%#&password=%#",[input objectForKey:#"email"], [input objectForKey:#"password"]];
NSString *hostStr = #"http://localhost/frissbee_peeyush/php/login.php?";
hostStr = [hostStr stringByAppendingString:post];
NSLog(#"HostStr %#",hostStr);
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(#"serverOutput %#", serverOutput);
What if i need to connect to url only using header information ?
Problem: for login and signup, these methods are perfectly fine but whenever i want to insert any string containing special characters such as #,/,_ etc, it is unable to perform any operation.
Guide me plz.
Even the method 1 you have implemented is incomplete as there are many delegates of NSUrlConnection which should be implemented to get the data , handling errors , proxy , authentication etc . It is more advisable to use the first method but not in the way you used.NSUrlConnection in asynchronous in behaviour so You Don't have to wait until the url is loaded.
NSUrlConnection Class Reference
The Second method simply hits the url as sson as it encounters the NSUrl parameter in the NSData . Moreover , you don't have much control over your web service interaction .
NSUrl Class Reference
To get the implementation of NSUrlConnection you can go through the
NSUrlConnection Tutorial
Url With Special Characters:-
[NSURL URLWithString:[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

Passing URL with parameter

I am passing url with some string value and NSInteger value in this url but when I put breakpoint on this and I tab on trace then it show me this message exc-bad-access in url I given bold please see that 'bold' I want to pass there value:
[ NSInteger day,NSInteger day1,NSString *fromDate1, NSString *fromDate1,NSString *OriginCode,NSString *DestinCode].
I get all value on url when I put the breakpoint but when I step into breakpoint my app crashes, why it crash? Help me. Where am I wrong?
-(void)sendRequest
{
stringWithFormat:#"http://www.google.com?AvailabilitySearchInputFRSearchView%24ButtonSubmit=Search%20For%20Flights%20&AvailabilitySeast=",day,day1,DestinCode,"2011-09","2011-09",OriginCode];
NSString *urlString = [NSString stringWithFormat:#"http://www.bookairways tickt.com/Sales/FRSearch.aspx?AvailabilitySearchInputFRSearchView%24ButtonSubmit=Search%20For%20Flights%20&AvailabilitySearchInputFRSearchView%24DropDownListMarketDay1=**%i**&AvailabilitySearchInputFRSearchView%24DropDownListMarketDay2=**%i**&AvailabilitySearchInputFRSearchView%24DropDownListMarketDestination1=**%#**&AvailabilitySearchInputFRSearchView%24DropDownListMarketMonth1=**%#**&AvailabilitySearchInputFRSearchView%24DropDownListMarketMonth2=**%#**&AvailabilitySearchInputFRSearchView%24DropDownListMarketOrigin1=**%#**&AvailabilitySearchInputFRSearchView%24DropDownListPassengerType_ADT=1&AvailabilitySearchInputFRSearchView%24DropDownListPassengerType_CHD=0&AvailabilitySearchInputFRSearchView%24DropDownListPassengerType_INFANT=0&AvailabilitySearchInputFRSearchView%24RadioButtonFlowSelector=FlightAndCar&AvailabilitySearchInputFRSearchView%24RadioButtonMarketStructure=RoundTrip&AvailabilitySearchInputFRSearchView%24discountPax=0&__EVENTARGUMENT=&__EVENTTARGET=&__VIEWSTATE=%2FwEPDwUBMGRkg4UKvNNb1NbM14%2F2n9zUxhNQ%2B%2BA%3D&errorlist=",day,day1,DestinCode,fromDate1,fromDate2,OriginCode];
//urlString=[urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
NSLog(#"************url:%#",url);
NSURLRequest *theRequest=[NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
} else {
}
}
make your url properly like this:-
NSURL *url = [NSURL URLWithString:[*yourstring* stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Harish this will help u to in creating the url check this our http://wiki.akosma.com/IPhone_URL_Schemes
like this
NSString *template = #"appigotodo://com.example.xyzapp/import?name=%#&note=%#&due-date=%#&priority=%#&repeat=%#";
NSString *name = #"Buy%20some%20milk";
NSString *note = #"Stop%20on%20the%20way%20home%20from%20work.";
NSString *dueDate = #"2009-07-16";
NSString *priority = #"1";
NSString *repeat = #"101";
NSString *stringURL = [NSString stringWithFormat:template, name, note, dueDate, priority, repeat];
NSURL *url = [NSURL URLWithString:stringURL];
[[UIApplication sharedApplication] openURL:url];
Two things:
The URL has many % symbols that are not being used as placeholders. The % symbols that are not between '**' in your code need to be escaped like so: %%. In other words, SearchInputFRSearchView%24Button should be SearchInputFRSearchView%%24Button.
You are using %i to put integers into your string. You should be using %d instead.

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.

how to send a word/text to a php file from iphone application

I am trying to send a word/text from my iphone application to php page, any idea?
You might do it with an asynchronous call.
// Prepare the URL
NSString myWord = #"YOUR_WORD";
NSString *urlString = [NSString stringWithFormat:#"http://<YOUR_DOMAIN>/<YOUR_FILE>.php?word=%#", myWord];
NSURL *url = [NSURL URLWithString:urlString];
// Get the data from the URL
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
// If you want to get an answer from this call then send "self" as delegate
// (and implement few NSURLConnectionDelegate methods),
// otherwise send "nil".
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection release];
[request release];
You might also send the word synchronously:
// Prepare the URL
NSString myWord = #"YOUR_WORD";
NSString *urlString = [NSString stringWithFormat:#"http://<YOUR_DOMAIN>/<YOUR_FILE>.php?word=%#", myWord];
// Get the data from the URL
NSError *error;
NSData *aData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:urlString] options:2 error:&error];
You would just have to load the URL with the word / text as a parameter using NSURLConnection. See the following for help in using NSURLConnection:
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836
And, some sample code:
// The word
NSString wrd = [NSString stringWithString:#"hello"];
// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.yourdomain.com/thepage.php?word=#%", wrd]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
receivedData = [[NSMutableData data] retain];
} else {
// Inform the user that the connection failed.
}

sending XML file from IPhone to a server using Post Method

I am trying to send the data to server from my Iphone client. It works fine for most values but when itry to send a string like "IPhone+Cocoa" the server shows the string as "IPhone Cocoa". I have tried to google it but without success is there any why of doing it.
Here is my code
-(void)sendRequest:(NSString *)aRequest
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:kURLRequest]];
NSString *httpBody = [NSString stringWithFormat:#"%#=%#",[requestString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[aRequest stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *aData = [httpBody dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:aData];
[request setHTTPMethod:#"POST"];
self.feedURLConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
Can anyone help me?
You do this for requestString and aRequest,but not after formatting together with your addition..
Try
httpBody = [httpBody stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
before
NSData *aData = [httpBody dataUsingEncoding:NSUTF8StringEncoding];