How to write http get and post in objective c? - ios

I want to use http Get and Post for getting the request and response of certain URL request,
But i dont know how to use them in objective c..
and Which one will come first Get or Post in establishment of connection.?
how to modify the content and post them back to the server..
Can any one please help me?

for get use :
+(NSMutableURLRequest*)getURq_getansascreen:(NSString*)ws_name {
NSLog(#"%#",ws_name);
NSMutableURLRequest *urlReq = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:ws_name] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[urlReq addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[urlReq setHTTPMethod:#"GET"];
return urlReq;
}
for post use :
+(NSMutableURLRequest*)postURq_getansascreen:(NSString*)ws_name :(NSString*)service {
NSString *tempUrl = domainURL;
NSString *msgLength = [NSString stringWithFormat:#"%d",[ws_name length]];
NSMutableURLRequest *urlReq = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#Service=%#",tempUrl,service]] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[urlReq addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlReq addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[urlReq setHTTPMethod:#"POST"];
[urlReq setHTTPBody: [ws_name dataUsingEncoding:NSUTF8StringEncoding]];
return urlReq;
}
//Call this in view did load as `
WSPContinuous *wspcontinuous = [[WSPContinuous alloc] initWithRequestForThread:[webService getURq_getansascreen:[webService GetDetails:str_filter]] sel:#selector(WS_GetDetailsLoaded:) andHandler:self];`
//create class WSPContinuous and add these fns..
-(id)initWithRequestForThread:(NSMutableURLRequest*)urlRequest sel:(SEL)seletor andHandler:(NSObject*)handler {
if (self=[super init]) {
self.MainHandler = handler;
self.targetSelector = seletor;
self.urlReq = urlRequest;
[self performSelectorOnMainThread:#selector(startParse) withObject:nil waitUntilDone:NO];
}
return (id)urlReq;
}
-(void)startParse{
NSLog(#"URL CALLING %#",urlReq.URL);
con = [[NSURLConnection alloc] initWithRequest:urlReq delegate:self];
if (con) {
myWebData = [[NSMutableData data] retain];
NSLog(#"myWebData old....%#",myWebData);
}
else {
[self.MainHandler performSelectorOnMainThread:targetSelector withObject:nil waitUntilDone:NO];
}
}
//-------------------------------connection-----------------
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[myWebData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[myWebData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
[self.MainHandler performSelectorOnMainThread:targetSelector withObject:nil waitUntilDone:NO];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *thexml = [[NSString alloc] initWithBytes:[myWebData mutableBytes] length:[myWebData length] encoding:NSUTF8StringEncoding];
NSLog(#"xmlDictionary %#",thexml);
[thexml release];
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLData:myWebData error:&parseError];
[AlertHandler hideAlert];
[MainHandler performSelector:targetSelector withObject:xmlDictionary];
}

If you want to start, a better idea would be to do some reading on NSMutableURLRequest and related topics like NSURLConnection.
You get sample code everywhere. Just google it.
Google search -> objective c get and post
and First hit -> Tutorials for using HTTP POST and GET on the iPhone in Objective-C

Related

IOS HttpPost not working

I am trying to send multiple parameter for a registration usage. Here is my Code for Posting data :
-(void)PostRegistrationData:(NSString *)userEmail :(NSString *)Password{
NSDictionary *params = #{
#"username":#"something",
#"password":#"aFilter",
#"email":#"aCategory",
#"type":#"aCategory",
#"request_type":#"aCategory"
};
/* We iterate the dictionary now
and append each pair to an array
formatted like <KEY>=<VALUE> */
NSMutableArray *pairs = [[NSMutableArray alloc] initWithCapacity:0];
for (NSString *key in params) {
[pairs addObject:[NSString stringWithFormat:#"%#=%#", key, params[key]]];
}
/* We finally join the pairs of our array
using the '&' */
NSString *requestParams = [pairs componentsJoinedByString:#"&"];
NSData *postData = [requestParams dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://teknofolk.com/spisrett_admin/slave/signup.php?"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
if( theConnection ){
// indicator.hidden = NO;
NSMutableData *mutableData = [[NSMutableData alloc]init];
}
}
But no data i getting inserted . Am i missing something?
You have various choices what you want to use.
First option:
NSURLResponse *res = nil;
NSError *err = nil;
NSData *retData = [NSURLConnection sendSynchronousRequest:request returningResponse:&res error:&err];
(you have also the async way for this option).
or you can also follow your code and continue with this:
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
and the request will be async and will call this methods (you need that this view controller responds to the NSURLConnectionDelegate and NSURLConnectionDataDelegate):
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse
*)response
{
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
It was my mistake in the parameter.
NSDictionary *params = #{
#"username":#"something",
#"password":#"aFilter",
#"email":#"aCategory",
#"type":#"aCategory",
#"request_type":#"aCategory"
};
Worked with simply this :
#"type":#"1",
#"request_type":#"2"
};
In my insertion i was passing wrong value on type and request type. Thanks to all for all

Why is didReceiveData function not working

I have a class which is used to get data from my server. The data returned from my server is in JSON. For some reason the didReceiveData won't run at all. I have placed NSLogs inside it to test it but it doesn't do anything?
Here is my code:
+(NSJSONSerialization *) getTask:(id)task_id{
NSString *post = [NSString stringWithFormat:#"&task_id=%#", task_id];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://my-server.com/"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn){
NSLog(#"Testing");
}
return json;
}
// Log the response for debugging
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {
NSLog(#"test");
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
}
// Declare any connection errors
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Error: %#", error);
}
Thanks,
Peter
getTask: is a class method, which means the self is the class. Therefore the delegate methods must also be class methods.
But note that you cannot return the received JSON from the getTask: method, because NSURLConnection works asynchronously.
You need to start the connection. Try using the initWithRequest:delegate:startImmediately: method:
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
or, just call the start method:
if(conn){
[conn start];
}

unable to fetch data as Post when Sending it as Post From IOS NSMutableURLRequest

this is the snippet to my Code, i am sending the code to a PHP page, but when i do print_r($_POST); i get empty Array, but when i do print_r($_GET) i get the variable which i am using to post the data i.e name but it also is empty, can any 1 sort out what i am doing wrong here
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)btnFetchData1:(id)sender {
// NSString *urlString = [NSString stringWithFormat:#"http://localhost/adi/adnan.php?name=%#", [self.txtName text]];
NSString *urlString = [NSString stringWithFormat:#"http://localhost/adi/adnan.php"];
NSString *post = [NSString stringWithFormat:#"name=%#",#"adnan"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
delegate:self];
if (conn) {
_receivedData=[NSMutableData data];
} else {
//something bad happened
}
}
#pragma NSUrlConnectionDelegate Methods
-(void)connection:(NSConnection*)conn didReceiveResponse:(NSURLResponse *)response
{
if (_receivedData == NULL) {
_receivedData = [[NSMutableData alloc] init];
}
[_receivedData setLength:0];
NSLog(#"didReceiveResponse: responseData length:(%d)", _receivedData.length);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error {
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Succeeded! Received %d bytes of data",[_receivedData length]);
NSString *responseText = [[NSString alloc] initWithData:_receivedData encoding: NSASCIIStringEncoding];
NSLog(#"Response: %#", responseText);
NSString *newLineStr = #"\n";
responseText = [responseText stringByReplacingOccurrencesOfString:#"<br />" withString:newLineStr];
[self.lblData setText:responseText];
}
You created postLength but never used it, try this it might solve it:
//create URL for the request
NSString *urlString = [NSString stringWithFormat:#"http://localhost/adi/adnan.php"];
//Post data
NSString *post = [NSString stringWithFormat:#"name=%#",#"adnan"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding]
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
//the request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
//Bind the request with Post data
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];

How to send big big string through NSURLConnection

This is my code.
- (void)loadData:(NSString *)url {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"connection found---------");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"reciving data---------");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"connection fail---------");
[self.pddelegate connectionError];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"data posting done---------");
[self.pddelegate dataPosted];
}
It is not working if url become bigger and give connection fail in logs.
Like
url=#".......order_details&admin=29&tableid=89&waiter_id=18&items=MzQ6MSwxMToxLDMzOjEsNjc6MSwzOToxLDY5OjEsNTY6MSw2ODoxLDg6MSw1NToxLDYyOjEsNzY6MSw0MToxLDIwOjEsNjE6MQ=="
see this SO post for get type request length What is the maximum length of a URL in different browsers?
for sending big string use POST type request instead of GET type.
We have there are two methods for sending data.
1. GET Method : Which is used for fixed length or limited length of string only.
2. POST Method : Which is used to send more string while comparing get method.
I have given the example Using PostMethod.
NSString *post =[[NSString alloc] initWithFormat:#"%#",YourString];
NSURL *url=[NSURL URLWithString:*#"YourURL like www.google.com"*];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[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];
request.timeoutInterval = 60;
NSError *error = nil;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
NSString *errStr = _stringEmpty;
#try { errStr = [error localizedDescription]; }#catch (NSException * exception){ }
If any error occur errStr will show the error.
In the past, I have used some URL's that are around 2000 characters in length in iOS with no problem. NSURL, NSURLRequest, and NSURLConnection all managed just fine. If your URL is shorter than that, the problem is probably not due to its length, but instead related to the way the URL is constructed.

JSON POST is not working in iOs

I am trying to post some data to the web service using JSON POST method, I have tried so many ways to do this, but none is working. Here is my code, please check:
NSArray *objects=[NSArray arrayWithObjects:#"value1", #"value2",#"value3", #"value4",#"value5", #"value6",#"value7", #"value8",#"value9", nil] ;
NSArray *keys=[NSArray arrayWithObjects:#"FirstName", #"LastName",#"UserName", #"Password",#"Email", #"Gender",#"DeviceId", #"DeviceName",#"ProfileImage", nil];
NSData *_jsonData=nil;
NSString *_jsonString=nil;
NSURL *url=[NSURL URLWithString:urlstring];
NSDictionary *JsonDictionary=[NSDictionary dictionaryWithObjects:objects forKeys:keys];
if([NSJSONSerialization isValidJSONObject:JsonDictionary]){
_jsonData=[NSJSONSerialization dataWithJSONObject:JsonDictionary options:0 error:nil];
_jsonString=[[NSString alloc]initWithData:_jsonData encoding:NSUTF8StringEncoding];
}
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
// [request setHTTPBody:_jsonData];
// [request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// [request setValue:[NSString stringWithFormat:#"%d", [_jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSString *finalString = [_jsonString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
[request setHTTPBody:[finalString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
// //return and test
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
Please check.
Here is a sample code am trying to register a user.
In the 'Register' button click,write the following code:
- (IBAction)registerButtonPressed:(id)sender
{
BOOL valid = FALSE;
valid=[self validateEntry];
if(valid)
{
NSString *bytes = [NSString stringWithFormat:#"{\"UserName\":\"%# %#\",\"Email\":\"%#\",\"UserType\":\"normaluser\",\"Password\":\"%#\"}",firstName,lastName,email,password];
NSURL *url=[NSURL URLWithString:urlstring];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[bytes dataUsingEncoding:NSUTF8StringEncoding]];
[self setUrlConnection:[NSURLConnection connectionWithRequest:request delegate:self]];
[self setResponseData:[NSMutableData data]];
[self.urlConnection start];
}
}
Then add the following as Connection delegate methods:
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.responseData setLength:0];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Network Status"
message:#"Sorry,Network is not available. Please try again later."
delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
if (connection == self.urlConnection)
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSError *error;
NSDictionary *jsonString=[NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&error];
if(jsonString != nil)
{
if ([[[jsonString objectForKey:#"data"] objectForKey:#"id"] length])
{
[[NSUserDefaults standardUserDefaults] setValue:[[jsonString objectForKey:#"data"] objectForKey:#"id"] forKey:#"user_id"];
[[NSUserDefaults standardUserDefaults] setValue:[[jsonString objectForKey:#"data"] objectForKey:#"UserName"] forKey:#"user_name"];
[[NSUserDefaults standardUserDefaults] synchronize];
[delegate userRegistrationViewControllerResponse:self];
}
else
{
UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:#"Info" message:[jsonString objectForKey:#"statusText"] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alertView show];
}
}
else
{
UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:#"Server Busy" message:#"Register after sometime" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alertView show];
}
}
}
This will post the user information as JSON.
Try this one....
NSURL *aUrl = [NSURL URLWithString:#"https://www.website.com/_api/Login/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:0.0];
[request setHTTPMethod:#"POST"];
NSString *postString = [NSString stringWithFormat:#"EmailAddress=%#&UserPassword=%#",uName.text,pwd.text];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
-Than call the NSURLConnection delegate methods.. dot forgot to alloc the responseData....
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
responseData = nil;
json =[[responseString JSONValue] retain];
NSLog(#"Dict here: %#", json);
}
The request should be something along these lines...
NSURL * url = [NSURL URLWithString:#"your_url"];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSError * error = nil;
NSData * postData = [NSJSONSerialization dataWithJSONObject:your_json_dictionary_here options:NSJSONReadingMutableContainers error:&error];
[request setHTTPBody:postData];
I also suggest to check your response to find out why is your request failing. Is it on the client side or server side (and why?)...

Resources