您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

Xcode 中使用 NSMutableURLRequest 以 POST 傳遞參數

編輯:iOS 7 技巧

下面介紹一個在蘋果開發工具 Xcode 中,使用 NSMutableURLRequest 以 POST 方式傳遞參數的測試範例,希望能幫助到各位朋友。

程式碼如下:

- (IBAction)upload:(id)sender {
 
    NSString *post = nil; 
 
    post = [[NSString alloc] initWithFormat:@"message=%@",@"hello,world."];
 
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
 
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; 
 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ; 
 
    [request setURL:[NSURL URLWithString:@"https://localhost/kids/sendimg.php"]]; 
 
    [request setHTTPMethod:@"POST"];
 
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
 
    [request setHTTPBody:postData]; 
 
    //[NSURLConnection connectionWithRequest:request delegate:self ]; 
 
 
 
    //同步請求的程式碼
 
    //returnData就是返回得到的資料
 
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
 
    NSString *result = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
 
 
 
    if(returnData)
     {
     NSLog(@"SOAP 返回 = %@",result);
     }
    else
    {
    NSLog(@"error!");
    }
 
}

對應的 PHP 端程式碼如下:

<?php
print_r($_POST);
?>

執行後,主控台會輸出如下的結果:

2014-09-18 15:16:21.346 Test9[31505:ef03] SOAP 返回 = Array
(
[message] => hello,world.
)

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved