I want to create an iPhone application to send data to a Rest API service. If the data is a string defined as geoX#35#geoY#65 which NSS method shall i use. Was thinking of NSString and NSMutablerequest to make my request and define my string but this isn't working atm.Also i am using NSURLconnection to establish a connection with the server(maybe that's faulty too). Anyone that can help ?
Thanks in advance.
Your connection data is using special characters and if you try to do this with GET method of NSURLConnection. It will Shows connection error. For this You have to use POST method like :
NSData *body = nil;
NSString *contentType = #"text/html; charset=utf-8";
NSURL *finalURL = #"YOUR URL WITH the ?input=";
NSString *yourString = #"geoX#35#geoY#65";
contentType = #"application/x-www-form-urlencoded; charset=utf-8";
body = [[NSString stringWithFormat:#"%#", yourString] dataUsingEncoding:NSUTF8StringEncoding];
if (nil==finalURL) {
finalURL = url;
}
NSMutableDictionary* headers = [[[NSMutableDictionary alloc] init] autorelease];
[headers setValue:contentType forKey:#"Content-Type"];
[headers setValue:mimeType forKey:#"Accept"];
[headers setValue:#"no-cache" forKey:#"Cache-Control"];
[headers setValue:#"no-cache" forKey:#"Pragma"];
[headers setValue:#"close" forKey:#"Connection"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:finalURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:body];
self.conn = [NSURLConnection connectionWithRequest:request delegate:self];
Related
What is nice and simple in C# is turning out to be a bear in Objective C
static private void AddUser(string Username, string Password)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://192.168.1.10:8080/DebugUser?userName=" + Username + "&password=" + Password));
request.Method = "POST";
request.ContentLength = 0;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.Write(response.StatusCode);
Console.ReadLine();
}
works fine, but when I try and convert it to Objective-C (IOS), all I get is "Connection State 405 Method not allowed"
-(void)try10{
NSLog(#"Web request started");
NSString *user = #"me#inc.com";
NSString *pwd = #"myEazyPassword";
NSString *post = [NSString stringWithFormat:#"username=%#&password=%#",user,pwd];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%ld", (unsigned long)[postData length]];
NSLog(#"Post Data: %#", post);
NSMutableURLRequest *request = [NSMutableURLRequest new];
[request setURL:[NSURL URLWithString:#"http://192.168.1.10:8080"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(theConnection){
webData = [NSMutableData data];
NSLog(#"connection initiated");
}
}
Any help or pointers to using POST on IOS would be a great help.
Those requests are not exactly the same.
C# example sends POST request to /DebugUser with query params ?userName=<username>&password=<password>, obj-c one sends POST request to / with form-urlencoded data userName=<username>&password=<password>. I guess that problem is this small mistake in URI path (mostly those small, stupid mistakes takes more time to solve than real problems.. ;) ). Additionally I would suggest to url encode params, in this example your username me#inc.com should be encoded as me%40inc.com to be valid url/form-url encoded data. See also my code-comment about ivar.
Something like that should work (written on the fly, I haven't compile that / check before posting):
-(void)try10{
NSString *user = #"me%40inc.com";
NSString *pwd = #"myEazyPassword";
NSString *myURLString = [NSString stringWithFormat:#"http://192.168.1.10:8080/DebugUser?username=%#&password=%#",user,pwd];
NSMutableURLRequest *request = [NSMutableURLRequest new];
[request setURL:[NSURL URLWithString:myURLString]];
[request setHTTPMethod:#"POST"];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(theConnection){
// I suppose this one is ivar, its safer to use #property
// unless you want to implement some custom setters / getters
//webData = [NSMutableData data];
self.webData = [NSMutableData data];
NSLog(#"connection initiated");
}
}
I am hitting a web service with array of objects. But in server side they are getting only null value for all the fields.
Client side code is:
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:urlRequest
delegate:self];
//************DATA formation
NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc]init];
NSMutableDictionary *jsonDict1 = [[NSMutableDictionary alloc]init];
[jsonDict setObject:#"3" forKey:#"rollNo"];
[jsonDict setObject:#"Ezhil" forKey:#"FirstName"];
[jsonDict setObject:#"Arasu" forKey:#"LastName"];
[jsonDict1 setObject:#"4" forKey:#"rollNo"];
[jsonDict1 setObject:#"XYZ" forKey:#"FirstName"];
[jsonDict1 setObject:#"ABC" forKey:#"LastName"];
NSArray *jsonArray=[[NSArray alloc]initWithObjects:jsonDict,jsonDict1, nil];
//Converting to JSON string.
SBJsonWriter *writer = [[SBJsonWriter alloc] init];
NSString *jsonString = [writer stringWithObject:jsonArray];
NSLog(#"JSON String : %#",jsonString);
//************Setting DATA in URL
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[connection start];
// Code for response....
I dont know were i went wrong. Can any one help me for this issue.
Thanks in advance.
I'd scrap the SBJson stuff and just use the native controls...
Do everything the same as you are doing but remove the SBJsonWriter stuff and do this to set the body of the request...
[urlRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:jsonArray options:NSJSONWritingPrettyPrinted error:&error]];
That should work.
Thank you.. Application is working fine without any modification. The problem is with server side. But i think we can go with your suggestion instead of using external framework.
In both the case I am getting the json object like this,
JSON String :
[{"rollNo":"3","FirstName":"Ezhil","LastName":"Arasu"},
{"rollNo":"4","FirstName":"XYZ","LastName":"ABC"}]
I managed to make an application to send data to a rest api service. The content type must be text/html. But whenever i run my app i get a 415 http code response which means not supported type of content. Here is my code:
NSURL *url = [NSURL new];
NSData *body = nil;
NSString *contentType = #"text/html";
NSURL *finalURL = [NSURL URLWithString:[NSString stringWithFormat:#"http://telesto.zapto.org:81/SMART_EdgeNode/EdgeNode/DataFeeds/3/addMeasurement"]];
NSString *yourString = #"geoX#35#geoY#65";
contentType = #"application/x-www-form-urlencoded; charset=utf-8";
body = [[NSString stringWithFormat:#"%#", yourString] dataUsingEncoding:NSUTF8StringEncoding];
NSString *putLength = [NSString stringWithFormat:#"%d",[body length]];
if (nil==finalURL) {
finalURL = url;
}
NSMutableDictionary* headers = [[[NSMutableDictionary alloc] init] autorelease];
[headers setValue:contentType forKey:#"Content-Type"];
[headers setValue:#"mimeType" forKey:#"Accept"];
[headers setValue:#"no-cache" forKey:#"Cache-Control"];
[headers setValue:#"no-cache" forKey:#"Pragma"];
[headers setValue:#"close" forKey:#"Connection"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:finalURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"PUT"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:body];
[request setValue:putLength forHTTPHeaderField:#"Content-Length"];
self.conn = [NSURLConnection connectionWithRequest:request delegate:self];
I guess atm there is something wrong with defining the content-type . Any help??
Thanks in advance
Ok i found it at last. It was this specific line that was causing the problem and had to do something with the content-type :
contentType = #"application/x-www-form-urlencoded; charset=utf-8";
After removing that i was able to send properly my string to the server.
I think the server's complaining that it doesn't know how to generate a response with the content type "mimeType".
Your Accept header should be "text/html" or whatever the content type you expect in the response, not "mimeType".
Update
After reading this again, I notice that you are setting the contentType to #"text/html", then to #"application/x-www-form-urlencoded; charset=utf-8". Which do you need? From the description, you want to sent text/html, but that is not what your sending. When you set contentType to #"application/x-www-form-urlencoded; charset=utf-8", text/html is lost.
What would be the reason for getting Invalid Request when we are posting an URL to server in iOS SDK. the URL what i am sending is correct and the data what I'm posting is also correct.
I tried in RestClient also even though I'm getting same error Invalid Request in that also.
Can any one help me what would be the reason for it.
Thanks in advance.
- (NSURLConnection *) executeAsyncHttpPost :(NSString *) baseURL :(NSString *) method
:(id) jsonParams :(int)callerTag
{
NSLog(#"jsonParams: %#", jsonParams);
NSString *urlstr = [NSString stringWithFormat:#"%#", baseURL];
urlstr = [urlstr stringByAppendingFormat:method];
NSLog(#"urlstr: %#", urlstr);
NSString *postLength = [NSString stringWithFormat:#"%d", [jsonParams length]];
NSURL *pUrl = [NSURL URLWithString:urlstr];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:pUrl];
NSData *requestData = [[NSData alloc] initWithData:[jsonParams dataUsingEncoding:NSASCIIStringEncoding]];
NSString* myString;
myString = [[NSString alloc] initWithData:requestData encoding:NSASCIIStringEncoding];
NSLog(#"myString: %#", myString);
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
self.tag = callerTag;
return [super initWithRequest:request delegate:delegateResponder];
}
The JSON you are posting might be invalid. Please validate it using this. There should be no character outside the { }.
Just post the following string instead of the current JSON
EDIT:
{"jsonRequest" :{"methodName":"CheckUserExist","username":"giriraj.vyas#dotsquares.com","password":"233444"}}
How do I make a synchronous request using RestKit?
I used earlier this way(SBJSON):
UIDevice *myDevice = [UIDevice currentDevice];
NSString *deviceUDID = [myDevice uniqueIdentifier];
double v = [[[UIDevice currentDevice] systemVersion]doubleValue];
NSString *version=[NSString stringWithFormat:#"%# %.1f",deviceType,v];
NSString *encodedParam1 =[version stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *requestString = [NSString stringWithFormat:#"method=views.get&view_name=client_list",nil];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSString *urlString = [NSString stringWithFormat:#"http://localhost/index.php?oper=StoreDeviceId&device_id=%#&device_version=%#",deviceUDID,encodedParam1];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
//Data returned by WebService
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
[request release];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSDictionary *dict1 = [returnString JSONValue];
same operation how to handle using restkit framework.
Advance thanks
Here is an example of a synchronous post using RKClient
//Configure RKLog
RKLogConfigureByName("RestKit/Network", RKLogLevelTrace);
//Set Client
RKClient *client = [RKClient clientWithBaseURLString:#"some_base_url"];
//Params to be send
NSDictionary *queryParameters = [NSDictionary dictionaryWithObjectsAndKeys:#"1",#"first_value",#"2",#"second_value",nil];
//Prepare the request and send it
RKRequest *request = [client post:#"path" params:queryParameters delegate:nil];
RKResponse *response = [request sendSynchronously];
//Process the response
NSString *stringResponse = [[NSString alloc] initWithData:[response body] encoding: NSUTF8StringEncoding];
NSDictionary *dict1 = [stringResponse JSONValue];
but I recommend to use asynchronous calls using blocks instead!.
To make a synchronous request using RestKit, use RKRequest's -sendSynchronously method after setting up the the RKRequest instance as normal.