I am trying to make a post request, but overtime I am getting error (coded in HTML). Here's my code:
if([mode isEqualToString:@"online"])
{
NSString *URL = [NSString stringWithFormat:@"http://130.1.5.183:9999/visit-reporting/content/visitreportservice/getCoverInfo"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]];
request.HTTPMethod = @"POST";
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSDictionary *jsonDictionary = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects: @"gds68342jhgdfk279364jkdbgfjksd82347", @"53afs", @"abc@def.com", @"2009-06-15T13:45:30", @"iPad", nil] forKeys:[NSArray arrayWithObjects:@"responseToken",@"userId", @"email", @"timeStamp", @"userAgent", nil]];
NSString *requestBodyData = [jsonDictionary description];
NSData *bodyData = [requestBodyData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = bodyData;
@try {
NSOperationQueue *q = [NSOperationQueue mainQueue];
[NSURLConnection sendAsynchronousRequest:request queue:q completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
NSMutableDictionary *parsedData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&connectionError];
if(!parsedData)
{
NSLog(@"Not able to parse data");
}
else
{
// DO something
}
}];
}
@catch (NSException *exception) {
NSLog(@"%@", [exception description]);
}
@finally {
}
}
else
{
//get cover information from offline database
}
However, when checking the response using a REST client (named COCOA REST CLIENT), the desired response is shown. Where is the issue?
This is the response I am getting when sending POST request from my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Error</title>
</head>
<body>
<p>An error has occured</p>
<p>Click <a href="javascript:history.go(-1)">here</a> to navigate back to the page you were on previously.</p>
<p>If this problem persists, please contact <a href="mailto:Support.vwg@vwg.co.uk?Subject=Visit Reporting Error&Body=Hi,%0D%0A%0D%0AI have been experiencing problems with the Visit Reporting application.%0D%0A%0D%0ACould you please look into this issue?">Support.vwg@vwg.co.uk</a></p>
</body>
</html>
This doesn't work as you expected:
NSString *requestBodyData = [jsonDictionary description];
You need to use NSJSONSerialization
's class method
dataWithJSONObject:options:error:
in order to get a NSData
object containing a sequence of UTF-8 characters from your NSDictionary
object.
See also: NSJSONSerialization Class Reference