1

我正在尝试从我的 iOS 应用程序将序列化对象发送到 Web 服务器,并且通常一切正常。我试过发送一个巨大的字符串,它在服务器上就很好了。但是当我将序列化对象发送到服务器时,字符串会被切断。我已经从我的应用程序中记录了字符串 - 它就在那里。我尝试将相同的字符串写入我的 Web 服务器上的文件,但它以最奇怪的方式被切断。

可能是什么原因?我怀疑这与编码有关。这是我将数据发送到服务器的方式:

+ (void)postRequestWithData:(id)data toURL:(NSURL *)url {
    // Prepare data
    NSData *postData = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil];
    NSString *postDataString = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
    NSString *requestString = [NSString stringWithFormat:@"sales=%@", postDataString];
    NSString *postLength = [NSString stringWithFormat:@"%d", [requestString length]];

    // Make the request
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    // Error reporting
    if (!connection) {
        NSLog(@"Could not make a connection!");
    }
}

其中 (id)data 是一个字典数组。

这是我在服务器中处理它的方式:

<?php
    $sales = $_POST['sales'];
    $myFile = "testFile.txt";
    $fh = fopen($myFile, 'w') or die("can't open file");
    fwrite($fh, $sales);
    fclose($fh);
?>
4

2 回答 2

0

您应该根据application/x-www-form-urlencode转义您的 URL(查询)字符串。为此有一个 NSString 函数:

- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding

据此,您的代码应如下所示:

NSData *postData = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil];
NSString *postDataString = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
NSSztring *escapedDataString = [postDataString stringByAddingPercentEscapesUsingEncoding:NSUTF8Encoding]
NSString *requestString = [NSString stringWithFormat:@"sales=%@", escapedDataString];
NSString *postLength = [NSString stringWithFormat:@"%d", [requestString length]];
于 2013-01-13T17:58:46.557 回答
-1

You need to URL encode your postDataString first. To do this you can use the Core Foundation function CFURLCreateStringByAddingPercentEscapes.

NSString *encoded = CFBridgingRelease( CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (__bridge CFStringRef)originalString, NULL, NULL, kCFStringEncodingUTF8 ) );

Both NULL parameters control which characters should be encoded and which should be left alone. Passing NULL for both escapes all characters that are invalid in URLs. Note that I am assuming ARC here.

Also your Content-Length calculation is wrong. You need to get the length from your NSData object, not the string.

于 2013-01-13T15:34:37.593 回答