1

I am using web service for my iOS app. I know how to send http post request via URL (not http Body) and get response using NSURLConnection Delegate. But now there is better approach which I am following for web service and passing parameters in request body. I looked for library on google and found this.

But the code is bit difficult for me and I suppose there should be function for the same, which can make this bit easier. Is there any? the code so far is below.

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] 
    initWithURL:[NSURL 
    URLWithString:**WebService URL**]];

[request setHTTPMethod:@"POST"];
[request setValue:@"text/json" forHTTPHeaderField:@"Content-type"];

NSString *jsonString = [NSString stringWithFormat:@"{\n\"username\":\"%@\",\n\"%@\":\"%@\",\n\"%@\":\"%@\",\n\"%@\":%@,\n\"%@\":%@,\n\"version\":%@,\n\"name\":\"%@\"\n}",userName, @"password",pass,@"accessToken",token,@"isOnline",@"True",@"accountType",type,@"False",name];

[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

[[NSURLConnection alloc] initWithRequest:request delegate:self];

jsonString in this code is the http body. I want to pass parameters in request body. Now, after executing this code i get null in NSData variable. whereas my web service function returns a value and also it returns if the execution was successful. what is wrong in my code. Thank you.

Community
  • 1
  • 1
xrnd
  • 1,273
  • 3
  • 21
  • 38

3 Answers3

5

Thanks for your answers. Finally I found the exact solution which works absolutely fine. I have used NSURLConnection delegate and I am passing parameter in HTTPBody in json. I am receiving response also in json. But sending parameter directly as json is not permitted in httprequestbody so we need to take it in NSData and set content-type.

Note: specifying content type is very important.

 -(void)sendDataToServer:(NSString*)userName :(NSString*)name{
 {
 NSArray *keys = [NSArray arrayWithObjects: @"name",@"accountType",@"isOnline",@"username", nil];
NSArray *objects = [NSArray arrayWithObjects:name,[NSNumber numberWithBool:false],[NSNumber numberWithBool:false],userName, nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

NSString *myJSONString =[jsonDictionary JSONRepresentation];
NSData *myJSONData =[myJSONString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"myJSONString :%@", myJSONString);
NSLog(@"myJSONData :%@", myJSONData);

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:Your URL string]];
[request setHTTPBody:myJSONData];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];


  if (theConnection) {
      NSLog(@"connected");
      receivedData=[[NSMutableData alloc]init];
  } else {

      NSLog(@"not connected");
  }

  }

  - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
   [receivedData setLength:0];
}

 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
NSString* responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"response: %@",responseString);
}

 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data
// receivedData is declared as a method instance elsewhere
NSLog(@"Succeeded! Received %lu data",(unsigned long)[receivedData length]);
NSString* responseString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(@"response: %@",responseString);


 NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableLeaves error:&myError];

// show all values

for(id key in res) {

    id value = [res objectForKey:key];

    NSString *keyAsString = (NSString *)key;
    NSString *valueAsString = (NSString *)value;

    NSLog(@"key: %@", keyAsString);
    NSLog(@"value: %@", valueAsString);
}  
}

P.S : You will need to add JSon files for serialization(json.h).

xrnd
  • 1,273
  • 3
  • 21
  • 38
  • @xmd Is JSON.h part of the Foundation library in iOS?? – Supertecnoboff Apr 15 '14 at 20:49
  • No, you can verify from here [link](https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/ObjC_classic/_index.html#//apple_ref/doc/uid/20001091). – xrnd Apr 22 '14 at 11:58
0

There is a typo in your sample code, this would explain the null result :

NSString ***jsonString** = [NSString stringWithFormat:@"{\n\"username\":\"%@\",\n\"%@\":\"%@\",\n\"%@\":\"%@\",\n\"%@\":%@,\n\"%@\":%@,\n\"version\":%@,\n\"name\":\"%@\"\n}",userName, @"password",pass,@"accessToken",token,@"isOnline",@"True",@"accountType",type,@"False",name];

[request setHTTPBody:[**xmlString** dataUsingEncoding:NSUTF8StringEncoding]];
Dhara
  • 4,093
  • 2
  • 36
  • 69
vdaubry
  • 11,369
  • 7
  • 54
  • 76
  • I just corrected my mistake in posting the question. but its not the same in my code. otherwise would give error. anyways now the main question, how to pass parameter in request body.?do you have any clue vdaubry? – xrnd Apr 09 '13 at 10:11
0

Check out this question nsurlrequest post body and this http post encode type

Generally, the body should conforms to "key=value" format

To your question, you need a "key" for your jsonString

[request setHTTPBody:[NSString stringWithFormat:@"postedJson=%@", jsonString]];

postedJson is the key through which you'll get the value of it at server side. such as:

request["postedJson"]

the value returned would be the jsonString you construted

Community
  • 1
  • 1
fengd
  • 7,551
  • 3
  • 41
  • 44
  • i tried the method mentioned. "key=value" but it returns 'string' does not contain a definition for 'username'. Now I am sure there is some mistake I am doing in my code or the format for http Body. this is my code now, `NSString *bodyContents =[NSString stringWithFormat:@"username=%@&password=%@&accessToken=%@&name=%@&version=%@&accountType=%@&isOnline=%@",userName,pass,token,name,@"false",@"false",@"false"]; ` – xrnd Apr 09 '13 at 19:24
  • @xmd, you don't get what i mean. please check the updated answer. – fengd Apr 10 '13 at 05:47
  • thanks @Jun1st. I have posted the solution which worked for me.Hope it helps – xrnd Apr 10 '13 at 08:29