NSString的initWithContentsOfFile无法加载任何zip文件。

问题描述:

服务器要求是将zip文件和一些字符串数据一起发布。 这里我面临2个问题。NSString的initWithContentsOfFile无法加载任何zip文件。

    在下面的代码
  1. "NSString *filecontent"价值为零。 (const char *)file是zip文件的路径
  2. 如何在服务器上发布数据。
- (void)postDataOnServerFilePath:(const char *)file withEmail:(const char *)email withDescription :(const char *)description withLanguage:(const char *)language { 
    NSError*error = nil; 
    NSString *content = [NSString stringWithUTF8String:file]; 
    NSString *filecontent = [[NSString alloc] initWithContentsOfFile:content encoding:NSUTF8StringEncoding error:&error]; 
    NSString *post = [NSString stringWithFormat:@"EMail=%s&Description=%s&Language=%s&Filename=%s&File=%@",email,description,language,file,filecontent]; 
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
    NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]]; 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
    [request setURL:[NSURL URLWithString:@"https://swlic.info/SharedDictionaries/userdictionary.ashx"]]; 
    [request setHTTPMethod:@"POST"]; 
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
    [request setHTTPBody:postData]; 
    NSHTTPURLResponse* response =[[NSHTTPURLResponse alloc] init]; 
    error = nil; 
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
    if (error){} 
    NSString *responseString = [[NSString alloc] initWithBytes:[responseData bytes] 
                 length:[responseData length] 
                 encoding:NSUTF8StringEncoding]; 
    NSLog(@"%@", responseString); 
} 
+0

一个zip文件*** ***不是一个NSUTF8StringEncoded字符串。你应该使用NSData。远程服务器期待什么样的数据格式? Base64编码或? –

+0

是的你是对的,我已经向我的客户建议这样做,但他要求我这样做,因为Web服务只是由此创建的,我的客户建议我使用NSUTF8StringEncoding进行编码。那么我会再次要求他们在这里使用NSData而不是NSString – kulss

可以发送二进制数据,文本,但你必须先进行编码的原始数据(例如,作为一个base64编码字符串)。

无论哪种方式,你的主要问题是你的数据都不是URL编码的。一个URL不能包含任意的二进制数据,也不能包含URL编码的POST主体。在将其添加到该字符串之前,您要插入到POST正文字符串(电子邮件等)中的每个值都需要进行URL编码。否则,某些cam会将&符号放入电子邮件地址并严重破坏。 (和一个ZIP文件包含这些禁用的字符。)

有关详细信息,请参阅:

https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/WorkingwithURLEncoding/WorkingwithURLEncoding.html