【问题标题】:iOS HTTP Post encoding for Hebrew characters希伯来语字符的 iOS HTTP Post 编码
【发布时间】:2013-08-22 10:38:38
【问题描述】:

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

这就是我正在做的:

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,但没有运气。

【问题讨论】:

  • @ahmedalkaff 你能更具体一点吗?我尝试了 NSUTF8StringEncoding 但只生成空字段,甚至不生成垃圾字符。
  • 我找到了这篇文章,您可以在其中检查数据的编码。希望这会有所帮助:link

标签: objective-c http-post urlencode


【解决方案1】:

选项 1

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

对您的帖子 NSString 进行 URL 编码并将编码更改为 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,请记住在 Project Settings -> Build Phases -> Compile Sources 下的库文件中添加 -fno-objc-arc 编译器标志.

【讨论】:

  • 关于选项 2,有一种更简单的方式来发送异步请求。检查here。谢谢@Tim Bodeit
  • 我确实意识到,您可以使用NSURLConnection 来执行异步请求。我之所以提到 ASIHTTPRequest,是因为它使 Post-Requests 变得更容易。不管是同步的还是异步的。
【解决方案2】:

(这主要解释了为什么需要 UTF-8 编码而不是 ASCII。我不打算解释这个问题的 URL 编码部分,因为 Tim Bodeit 已经做得很好了。)

基本解释:

ASCII 编码只包含英文、非重音字符,而 UTF-8 包含大多数语言的字符。

详情:

ASCII 仅包含下图中显示的字符,尽管它仅适合七位(或八位,取决于您看待它的方式)。

但是,Unicode 和 UTF-8 都可以包含几乎所有主要语言的任何字符。 UTF-8 优于 Unicode,因为当您的应用程序使用 ASCII(英文)字符时,它将只有一个字节。当您的应用程序使用希伯来语时,字符串会长几个字节。如果你使用 Unicode,你的字符串总是多于一个字节,无论是英语还是希伯来语。

解决方案?只需将所有显示 ASCII 的内容更改为 UTF8。

您(和所有其他程序员)应该绝对阅读this article

它由 Joel Spolsky(Stack Exchange 的联合创始人)编写,它对任何使用字符串的程序(大多数程序)都非常有益。如果您同时使用希伯来语和英语工作,您将特别受益。

顺便说一句,你应该删除标签 iOS、iPhone、iPad,并用 Objective-C 替换它,因为你的代码 sn-p 也可以应用于 Mac 的编程。

【讨论】:

    【解决方案3】:

    Swift 4 转义包含希伯来语字符串的解决方案

    let dataString = "firstname=בני&lastname=דוידוביץ".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? ""
    
    let urlString = "http://be.repoai.com:5080/WebRTCAppEE/streams/home/משדר_מיוחד_לכבוד_יום_הזעכרון_לחללי_מערכות_ישראל_ופעולות_האיבה.mp4".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? ""
    

    【讨论】:

      【解决方案4】:

      对于希伯来语字符,使用 NSUTF8StringEncoding 在服务器上发布数据

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

      【讨论】:

        【解决方案5】:

        您可以使用AFNetworking,这会将您的数据以 utf-8 编码发送

        NSString *encodeUrl  = [@"document/d/Hphb4NsfxZLxTl7p3LMCWCpm9MCWskgoTFWzhP1Fpqap/edit" stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];  
        
        //setup the post using AFHTTPClient  
        AFHTTPClient *afHttpRequest = [[[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"https://docs.google.com"]] autorelease];  
        NSURLRequest *request = [afHttpRequest requestWithMethod:@"POST" path:encodeUrl parameters:post];  
        
        //loading indicator  
        [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];  
        [[AFNetworkActivityIndicatorManager sharedManager] incrementActivityCount];  
        
        [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];  
        AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request  
            success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON){  
                //some response  
            }  
            failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){  
                //the request fails  
            }  
        ];  
        //fire the request  
        [operation start]; 
        

        什么是 [Util append] ?向字段添加一些额外的编码?或者只是追加

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-07-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-16
          相关资源
          最近更新 更多