[希伯来字符的iOS HTTP Post编码

问题描述 投票:8回答:5

我需要从我的iPhone应用程序向Google文档进行HTTP发布。它适用于英语,但希伯来语在Google文档中显示为问号。

这是我正在做的:

NSString *post = [Util append:@"&entry.xxxxx=", self.firstName.text, @"&entry.yyyyyyy=", self.phone.text, @"&entry.zzzzzzzz=", self.email.text, nil];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"https://docs.google.com/forms/d/FORM_ID/formResponse"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];

我想念的是什么?

编辑:我尝试了提供的here解决方案,并查看了ahmedalkaf的链接here,但没有运气。

objective-c http-post urlencode
5个回答
3
投票

选项1

您已将Content-Type设置为application/x-www-form-urlencoded,但尚未对内容进行url编码。

对您的帖子NSString进行URL编码,然后将Encoding更改为UTF-8(我不能告诉您原因,但是需要使其生效)。>>

NSString *post = [Util append:@"&entry.xxxxx=", self.firstName.text, @"&entry.yyyyyyy=", self.phone.text, @"&entry.zzzzzzzz=", self.email.text, nil];
post =[post stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

其他所有东西都可以保持不变。但是,您应该考虑使用异步请求。使用同步请求时,您的用户界面将变得无响应,直到请求完成为止。异步请求不会发生这种情况。

选项2

对于HTTP请求,我通常使用ASIHTTPRequest库:http://allseeing-i.com/ASIHTTPRequest/

整合到您的项目中需要花费几分钟,但是这使一切变得更加简单。您不必弄乱编码等。

NSURL *url =[NSURL URLWithString:@"https://docs.google.com/forms/d/FORM_ID/formResponse"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];

[request addPostValue:self.firstName.text forKey:@"entry.xxxx"];
[request addPostValue:self.phone.text forKey:@"entry.yyyy"];
[request addPostValue:self.email.text forKey:@"entry.zzzz"];

[request startAsynchronous];

就是这样。

要设置ASIHTTPRequest,请遵循以下说明http://allseeing-i.com/ASIHTTPRequest/Setup-instructions,如果使用ARC,请记住在项目设置->构建阶段->编译源

下的库文件中添加-fno-objc-arc编译器标志。

3
投票

((这主要解释了为什么需要通过ASCII进行UTF-8编码。我不会解释此问题的URL编码部分,因为Tim Bodeit已经做得很好。)


1
投票
用于希伯来字符将数据发布到服务器上使用的NSUTF8StringEncoding

1
投票
[您可以使用AFNetworking,它将以utf-8编码发送您的数据,我将这个库用于西班牙语项目,并且始终获得áéóúñ的正确字符:

1
投票
Swift 4转义包含希伯来语的字符串的解决方案
© www.soinside.com 2019 - 2024. All rights reserved.