How to send data in url to server? - ios

http://novatoresols.com/demos/blow/users/add.json?json={"email":"ali"}
How can I send a key and data to web? Here "email" is the key and "ali" is the value in URL.
Code:
NSURL *url=[NSURL URLWithString:[hostURL stringByAppendingFormat:#"users/add.json?json="]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString * params =#"{\"email\":\"Ali\"}";
[request setHTTPMethod:#"POST"];
// This is how we set header fields
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

Simply Try with this :
NSString * params =#"{\"email\":\"Ali\"}";
NSURL *url=[NSURL URLWithString:[hostURL stringByAppendingFormat:#"users/add.json?json=%#",params]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog (#"%#",data);

Related

Login using Tinder API

I am using https://gist.github.com/rtt/10403467 for reference but I am not able to login into Tinder. I get a blank response.
NSURL *url = [NSURL URLWithString:#"https://api.gotinder.com/auth"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
//NSString *str = [NSString stringWithFormat:#"{\"facebook_token\": %#, \"facebook_id\": %#}",accessToken,userID];
NSDictionary *dataDict = [NSDictionary dictionaryWithObjectsAndKeys:accessToken, #"facebook_token", userID, #"facebook_id", nil];
NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dataDict
options:NSJSONReadingAllowFragments
error:nil];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
//[request setHTTPBody:[str dataUsingEncoding:NSASCIIStringEncoding]];
[request setHTTPBody:dataFromDict];
[request setValue:#"Tinder/4.1.4 (iPhone; iOS 9.3; Scale/2.00)" forHTTPHeaderField:#"User-Agent"];
[request setValue:#"ios" forHTTPHeaderField:#"platform"];
[request setValue:#"1.0" forHTTPHeaderField:#"app-version"];
[request setValue:[NSString stringWithFormat:#"%lu",[dataFromDict length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];
[connection start];
Please help

Sending Post http request from nsstring

I have this json:
{"myFriends":{"userId":"the user id", "userName":"the user name", "friends":[{"u":"friend user id","n":"friend user name"},{"u":"friend user id","n":"friend user name"}]}}
and I want to send him in post request to the server, this is the current way I am trying to do this:
+(NSData *)postDataToUrl:(NSString*)urlString :(NSString*)jsonString
{
NSData* responseData = nil;
NSURL *url=[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
responseData = [NSMutableData data] ;
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
NSString *bodydata=[NSString stringWithFormat:#"%#",jsonString];
[request setHTTPMethod:#"POST"];
NSData *req=[NSData dataWithBytes:[bodydata UTF8String] length:[bodydata length]];
[request setHTTPBody:req];
NSURLResponse* response;
NSError* error = nil;
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"the final output is:%#",responseString);
return responseData;
}
The json string contains the json, but for some reason the server always get nil and return error. How to fix this?
It would certainly help to tell your server about the content type:
[request addValue:#"application/json"
forHTTPHeaderField:#"Content-Type"];
Furthermore: in my own code I use:
[request setHTTPBody:[bodydata dataUsingEncoding:NSUTF8StringEncoding]]
This is my code for POST request with an NSData parameter:
- (void)uploadJSONData:(NSData*)jsonData toPath:(NSString*)urlString {
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:kRequestTimeout];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: data];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[data length]] forHTTPHeaderField:#"Content-Length"];
// Create url connection and fire request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[connection start];
}
This is for an asynchronous request, but it should work just fine for synchronous. The only thing I see you might be missing is the "Content-Length" parameter.

Http GET and POST method in ios

i need to post my value to the test WebView i try'd but my value didnt post and no change while iam running
NSString *post = [NSString stringWithFormat:#"643c30f73a"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"XXXXX.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];
Are you implementing the required delegate methods for NSURLConnection?
See the documentation at https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html for details and example implementations.
Implementing the delegate methods will at least give you an indication of any error that is occurring.
its worked for me,
NSURL *url = [NSURL URLWithString: #"http://your_url.com"];
NSString *body = [NSString stringWithFormat: #"arg1=%#&arg2=%#", #"val1",#"val2"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];
[request setHTTPMethod: #"POST"];
[request setHTTPBody: [body dataUsingEncoding: NSUTF8StringEncoding]];
[webView loadRequest: request];

How to Use Cache Memory concept in objective-c

// Web service request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
NSError *respError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
//returndata is response of webservice
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSDictionary *results = [responseString JSONValue] ;
NSLog(#"chat data- %#",results);
NSString *strResults = [results objectForKey:#"d"];
NSLog(#"result string is-%#",strResults);
this is the code that I am using for my Data fetching from web service. But i have to do this every time when come to this page.
Is that any method that can store my data in Cache memory so i need not to request every time.
I Am using
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
but i dont know how to use - (NSCachedURLResponse *) connection this method
thanks...
You need to use cache as of your needs according to this documentation: whenever you requesting a NSMutableURLRequest...
For Ex:
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60];
For More details Kindly look into the Documentation

Fields to be set in HTTP header

I am calling a web service in iOS. For this, I need to set the header in NSMutableURLRequest object. My service takes two string parameters and returns data in JSON format.
What are the the fields that I need to set in the header (Both while using GET and POST) using the setValue:forHTTPHeaderField:.
We do not need to use setHTTPBody: while using GET.. right???
I had the same question and I resolved (using some code from Iducool and Ankit Mehta) like this...
NSURL *theURL = [NSURL URLWithString:#"yourURL"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];
//Specify method of request(Get or Post)
[theRequest setHTTPMethod:#"GET"];
//Pass some default parameter(like content-type etc.)
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[theRequest setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
//Now pass your own parameter
[theRequest setValue:yourValue forHTTPHeaderField:theNameOfThePropertyValue];
NSURLResponse *theResponse = NULL;
NSError *theError = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
//Now you can create a NSDictionary with NSJSONSerialization
NSDictionary *dataDictionaryResponse = [NSJSONSerialization JSONObjectWithData:theResponseData options:0 error:&theError];
NSLog(#"url to send request= %#",theURL);
NSLog(#"%#",dataDictionaryResponse);
Look at this code which i am using to call a web service and thats working for me
+(NSString *)http_post_method_changed:(NSString *)url content:(NSString *)jsonContent{
NSURL *theURL = [NSURL URLWithString:url];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];
NSData *requestData = [jsonContent dataUsingEncoding:NSUTF8StringEncoding];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[theRequest setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[theRequest setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody: requestData];
NSURLResponse *theResponse = NULL;
NSError *theError = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
NSString *data=[[NSString alloc]initWithData:theResponseData encoding:NSUTF8StringEncoding];
NSLog(#"url to send request= %#",url);
NSLog(#"response1111:-%#",data);
return data;
}
Both while using GET and POST We do not need to use setHTTPBody?
setHTTPBody only make sense when you are using POST request. GET don't need it.
For Header parameters do something like below
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];
//Specify method of request(Get or Post)
[theRequest setHTTPMethod:#"GET"];
//Pass some default parameter(like content-type etc.)
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[theRequest setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
//Now pass your own parameter
[theRequest setValue:yourObj forHTTPHeaderField:#"your parameter name"];
setHTTPBody is used when HTTP method POST is being used.
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:theUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:120.0];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:data];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Here the data is nothing but NSData of JSON data that need's to be sent.

Resources