我正在尝试发布帖子请求,但是超时我收到错误(用HTML编码)。这是我的代码:
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
}
但是,使用REST客户端(名为COCOA REST CLIENT)检查响应时,会显示所需的响应。我无法理解问题所在。请帮助。
这是我从代码发送POST请求时得到的响应:
<!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>
答案 0 :(得分:1)
这不符合您的预期:
NSString *requestBodyData = [jsonDictionary description];
您需要使用NSJSONSerialization
的类方法
dataWithJSONObject:options:error:
为了从NSData
对象获取包含UTF-8字符序列的NSDictionary
对象。
答案 1 :(得分:0)
我看到的第一件事是您正在使用POST请求并发布数据但未设置@“Content-Length”
所以添加:
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[bodyData length]] forHTTPHeaderField:@"Content-Length"];
在运行连接之前