NSMutableURLRequest在设备上发送空值但在浏览器中有效

时间:2012-11-26 23:32:50

标签: ios objective-c iphone nsmutableurlrequest

在您阅读本文之前,请记住,我是一名Objective C程序员,试图帮助调查C#程序员的服务器问题,而C#程序员对我的工作一无所知。

我正在向.net / c#端发送SOAP数据包,服务器接收变量的空值。当url和变量字符串放入浏览器时,我得到了正确的响应。

帖子注销“?help = 1& email=test@email.net& password = testpassword”,但我不断收到“结果=错误&详细信息=对象引用未设置为对象的实例”。返回我的返回字符串。

NSString *post = [NSString stringWithFormat:@"?help=1& email=? & password=%@",userEmail, userPassword];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];


NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:LOGIN_SERVICE]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

//Submit the Post:
[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

/NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

//Extract Return:
NSString *returnString = [[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];

1 个答案:

答案 0 :(得分:2)

格式字符串中的电子邮件变量未填充。而且,为什么你的帖子数据中有空格?我想这会引起你的问题。因为您的数据可以包含空格,所以您需要将它们转义。

而不是:

NSString *post = [NSString stringWithFormat:@"?help=1& email=? & password=%@",userEmail, userPassword];

尝试:

NSString* escapedUserEmail = [userEmail stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSString* escapedUserPassword = [userPassword stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

NSString *post = [NSString stringWithFormat:@"?help=1&email=%@&password=%@",escapedUserEmail, escapedUserPassword];

有关该主题的更多阅读,请参阅:http://deusty.blogspot.com/2006/11/sending-http-get-and-post-from-cocoa.html