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

时间:2016-12-21 06:43:08

标签: macos nsurlconnection

服务器要求是发布zip文件以及一些字符串数据。 在这里,我面临着两个问题。

  
      
  1. 在下面的代码中,"NSString *filecontent"值为零。其中(const char *)file是zip文件的路径
  2.   
  3. 如何在服务器上发布数据。
  4.   
- (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);
}

1 个答案:

答案 0 :(得分:0)

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

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

详情请见:

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