JSON Post request error
I am trying to send user details from registration page in a dictionary using JSON but it shows error "Request without data". How do I fix this?
Here is the code:
NSString *jsonString = [dicRegister JSONRepresentation];
NSData *jsonData = [NSData data];
jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableString *string1 = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"jsonData: %@", string1);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.xyz.com/phpFile/methodName/"]];
NSMutableData *requestData = [[NSMutableData alloc] initWithBytes:[jsonString UTF8String] length:[jsonString length]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderFiel开发者_如何转开发d:@"Content-Type"];
[request setValue:@"json" forHTTPHeaderField:@"Data-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(@"returnData: %@", returnString);
If the issue is not with the server it is possible you could be sending an incorrect length to the web service. Since you are using [jsonString UTF8String]
you should also use [jsonString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]
. The documentation says that length returns the count of unicode characters.
Example:
NSString *sample = @"El Niño";
NSLog(@"length: %d utf8length: %d",[sample length], [sample lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
produces the output
length: 7 utf8length: 8
The reason is ñ requires 2 UTF8 characters to represent it.
Code here is okay...there was an error on server side php method....Any way thanx all for your help. :)
精彩评论