我正在尝试在服务器上的文本文件中的服务器上上传label.text,这是我的代码。它没有显示任何错误,但文件在服务器上创建但没有文本。请帮忙。
NSString *post =[[NSString alloc] initWithFormat:@"VIN: %@",vincode.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData
length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init]
autorelease];
[request setURL:[NSURL URLWithString:@"Server Detail Here/upload_vin.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded"
forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSData *urlData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSLog(@"Succeeded! Received %d bytes of data",[urlData length]);
NSLog(@"VIN is %@",vincode.text);
NSString *outputdata = [[NSString alloc] initWithData:urlData
encoding:NSASCIIStringEncoding];
NSLog(@"Outputdata is %@",outputdata);
NSURLResponse *response;
NSError *error;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(error==nil)
NSLog(@"Error is nil");
else
NSLog(@"Error is not nil");
NSLog(@"success!");
PHP file::::::::::::::
<?php
$file = "VinCodes.txt";
#$submitted_vincode = $_GET['VIN'] . " \n";
$submitted_vincode = @$_POST['VIN'] . " \n";
if(!empty($submitted_vincode)){
$Handle = fopen($file, 'a');
fwrite($Handle, $submitted_vincode);
print "Vin Code stored in file.";
fclose($Handle);
}else{
print "Vin code is missing. Try again";
}
?>
答案 0 :(得分:0)
方法代码很多,这是我的工作,(注意我上传异步):
NSURL *url = [NSURL URLWithString: @"http://..."];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:data];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[NSURLConnection sendAsynchronousRequest:request ...
顺便说一下,你确定要NSASCIIStringEncoding
而不是NSUTF8StringEncoding
吗?
如果有疑问,我使用Charles Web代理(30天免费)可以准确查看发送的内容和响应。