2011-05-21 16 views
0

我有目標C代碼創建一個NSURLConnection的如下:如何從PHP中的iPhone應用程序響應POST?

//prepar request 
    NSString *urlString = [NSString stringWithFormat:@"http://ctruman.info/post.php"]; 
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; 
    [request setURL:[NSURL URLWithString:urlString]]; 
    [request setHTTPMethod:@"POST"]; 

    //set headers 
    NSString *contentType = [NSString stringWithFormat:@"text/xml"]; 
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; 

    //create the body 
    NSString *formData = [[NSString alloc] initWithFormat:@"%@ %@", username.text, password.text]; 

    NSData *postData = [[NSString stringWithString:formData] dataUsingEncoding:NSUTF8StringEncoding]; 

    //post 
    [request setHTTPBody:postData]; 

    //get response 
    NSHTTPURLResponse* urlResponse = nil; 
    NSError *error = [[NSError alloc] init]; 
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error]; 
    NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
    NSLog(@"Response Code: %d", [urlResponse statusCode]); 
    if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) { 
     NSLog(@"Response: %@", result); 
    } 

然後,我有一個應該閱讀我的文章變量PHP腳本正在發送:

<?php 
print('<pre>'); 
print_r($_POST); 
print('</pre>'); 
?> 

當我執行此,NSLog吐出以下內容:

Array 
    (
    )
爲什麼不打印出我的發佈變量?我是否錯誤地發出POST請求?

回答

2

就我而言,PHP試圖讀取您的POST提交,就好像它是一個格式正確的PHP POST有效內容。相反,您將內容類型設置爲XML內容 - 這可能會混淆PHP。它正在尋找編碼變量,並尋找XML。

你有2種選擇:

  1. 閱讀在XML和使用PHP解析它自己: $ XML =的file_get_contents( 'PHP://輸入'); 讀取輸入一個例子是在這裏:http://www.codediesel.com/php/reading-raw-post-data-in-php/ 那麼你可以用PHP的XML支持解析它:http://us.php.net/xml

  2. 重新編碼你的目標,到剛剛發送正常POST參數到服務器。我使用ASIHTTPRequest庫,這很容易。 http://allseeing-i.com/ASIHTTPRequest/

+0

這很酷。我不知道那個PHP://輸入 – chustar 2011-05-22 01:19:01

1

以下代碼工作正常。

目標C

NSString *name = @"Anne"; // encode this 
NSString *pass = @"p4ssw0rd"; // encode this 
NSString *requestString = [NSString stringWithFormat:@"&name=%@&pass=%@",name,pass]; 
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]]; 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://localhost/post.php"]]; 
[request setHTTPMethod: @"POST"]; 
[request setHTTPBody: requestData]; 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; 
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil]; 
NSString *resultString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; 
NSLog(@"%@",resultString); 

PHP

<?php 

print_r($_POST); 

?> 

結果

Array 
(
    [name] => Anne 
    [pass] => p4ssw0rd 
) 

替代

結帳ASIHTTPRequest:
http://allseeing-i.com/ASIHTTPRequest/

+0

這很好,謝謝!錯誤與我的內容類型和使請求字符串爲UTF8String。 – 2011-05-22 06:05:54

相關問題