[英]HTTP post NSString into php file on server
我需要將NSString發布到網站上的文件中。 我已經在http://www.mysite.herokuapp.com/newFile.php創建了一個文件,需要將數據發布到newFile.php中。
我在iOS中找到了此“ 將字符串發送到Web服務器”? 之前,我認為是完美的,但很快意識到是從2009/2010年開始的,此代碼無法正常工作。 稍微擺弄一下之后,我得到了下面的代碼,但是它不起作用。
因此,有兩個部分:
首先,我應該甚至張貼到PHP文件擺在首位? .txt會更容易嗎?
第二,如何在網站端和iOS端執行此操作?
這是我在iOS中編寫的代碼:
// Post data onto external server
NSString *post = @"IsThisWorking?";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"https://mysite.herokuapp.com/getLikes.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
獲取ASIHttpRequest或AFNetworking。
我使用ASIHttpRequest及其ASIFormData,因為我發現AFNetworking有一些POST變量錯誤:
-(void)postDataToServer
{
NSURl url = [NSURL urlWithString:@"http://www.myserver.com/api/submitdata"];
__block ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:myString forKey:@"data"];
[request setCompletionBlock:^{
NSLog(@"Server response = %@", [request responseString]);
}];
[request setFailedBlock:^{
NSLog(@"Server error: %@", [[request error] localizedDescription];
}];
[request startAsynchronous];
}
我將使用像Symfony這樣的Web框架來構建Web服務,但是對於快速又骯臟的解決方案,您可以執行以下操作來快速測試:
class API
{
public function saveData()
{
if(isset($_REQUEST['data']))
{
// google some php code to write to file
}
}
}
// when the page loads, we call the saveData and in there
// we check if data is passed in
$api = new API();
$api->saveData();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.