1

Hi I want to post XML data within JSON Object.

This is the way i post

[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
NSString *postString = [NSString stringWithFormat:@"{\"UserId\":\"%@\",\"UserDataXML\":\"%@\"}",@"USRfa9210bad85165d5",@"<Root Bookmark=\"Page1\">\\u000d\\u000a  <Name>MyName<\Name>\\u000d\\u000a <Address>MyAddress<\ Address></Root>"];
NSData  *requestData =  [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:requestData];

In connectionDidFinishLoading _responseData is come,But responsedict is getting Null. Where i am going wrong?

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{       
      NSLog(@"_responseData %@",_responseData);
      NSString *responseString = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
      NSError *error;
      NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
      NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
      NSLog(@"responseDict %@",responseDict);
}
Maulik
  • 19,348
  • 14
  • 82
  • 137
pallavi_dev
  • 85
  • 1
  • 9

1 Answers1

0

First of all, you must escape your JSON before use.

And then,

(1) If the server is only responding with a form-data, a post data must be a pair of key and value.

NSString *postString = [NSString stringWithFormat:@"UserId=%@&UserDataXML=%@",
    @"USRfa9210bad85165d5",
    @"<Root Bookmark=\\\"Page1\\\">\\u000d\\u000a<Name>MyName</Name>\\u000d\\u000a<Address>MyAddress</Address></Root>"];

(2) If the server is only responding with JSON, Content-Type should be set to "application/json" and then,

NSString *postString = [NSString stringWithFormat:@"{\"UserId\":\"%@\", \"UserDataXML\":\"%@\"}",
    @"USRfa9210bad85165d5",
    @"<Root Bookmark=\\\"Page1\\\">\\u000d\\u000a<Name>MyName</Name>\\u000d\\u000a<Address>MyAddress</Address></Root>"];

BTW, have you checked the variable '_responseData'? I think it's also empty.

piljoong
  • 371
  • 1
  • 3