2012-11-30 87 views
1

我使用以下代码将数组发送到php服务器,但在php端他们没有收到任何值。我将数组作为json字符串发送。如何使用web服务将json数组发布到Php服务器

- (void)postArray { 
//Create the URL request 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://test.com./t.php"]]; 
    NSMutableArray *array = [[NSMutableArray alloc] init]; 
    [array addObject:@"one"]; 
    [array addObject:@"Two"]; 
    [array addObject:@"three"]; 
    [array addObject:@"four"]; 
    [request setHTTPMethod:@"POST"]; 
    // NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:array,@"comment", nil]; 
    SBJSON *parser =[[SBJSON alloc] init]; 
    // NSString *jsonString = [parser stringWithObject:dict]; 
    NSString *jsonString = [parser stringWithObject:array]; 
    NSLog(@"Str %@",jsonString); 
    [request setValue:@"application/x-www-form-urlencoded" 
    forHTTPHeaderField:@"Content-Type"]; 
    [request setValue:jsonString forHTTPHeaderField:@"comment"]; 
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 

     NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response; 
     NSInteger statusCode = [HTTPResponse statusCode]; 


     if (statusCode==200) { 


      //Request goes in success 
      NSError* error; 
      NSMutableDictionary* json = [NSJSONSerialization 
             JSONObjectWithData:data //1 
             options:kNilOptions 
             error:&error]; 
      NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 


      NSLog(@"Json for post array ----------%@",str); 

     }else{ 

      ///request is get failed 

      NSLog(@"Error Description %@",[error description]); 
     } 
    }]; 

    [request release]; 


} 

与输出在PHP是

<预> <BR>这是响应从iPhone <BR>首先<BR> <BR>端 首先<BR>第二接收JSON越来越响应和解码json 响应<br>从commaArrayBR > nullThird断裂( [0] =>)

这里是PHP代码

<?php 

echo "<pre>"; 
echo "<br>"; 
//echo "Testing array"; 
$totalitem=$_POST['total']; 
echo "This is response getting from the Iphone"; 
echo "<br>"; 
echo "First"; 
echo $jsonarray1=$_POST['comment']; 
echo "<br>"; 
print_r($jsonarray1); 
echo "<br>"; 
echo "end First"; 
echo "<br>"; 



echo "Second receive json response and decode the json response"; 
echo "<br>"; 
echo $comment=$_POST['comment']; 
echo "<br>"; 
$jsonarray=json_decode($comment); 
echo json_encode($jsonarray); 


echo "Third Breaking from comma"; 
echo "<br>"; 
$allval=explode(',',$jsonarray1); 
print_r($allval); 

?> 

请帮助

+0

邮报出从PHP – Codesen

+0

把这是应对来自iPhone 第一端得到第一个 第二个接收json响应并解码json响应 null3rd从commaArray([0] =>) – iProgrammer

+0

同样msg他们重定向到iphone – iProgrammer

回答

0

尝试下面的代码可以对你有所帮助。尝试创建一个NSMutableDictionary然后POST。

 NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary]; 
     [dictionnary setObject:@"First" forKey:@"First"]; 


     NSError *error = nil; 
     NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary 
                  options:kNilOptions 
                  error:&error]; 

     NSString *urlString [email protected]"Your URL"; 

     NSURL *url = [NSURL URLWithString:urlString]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
     [request setHTTPMethod:@"POST"]; 

     [request setHTTPBody:jsonData]; 
     NSURLResponse *response = NULL; 
     NSError *requestError = NULL; 
     NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError]; 
     NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ; 
     NSLog(@"%@", responseString); 
+0

okk的原始输出。让我试试这个 – iProgrammer

+0

不工作...仍然有相同的响应 – iProgrammer

+0

检查此链接:http://stackoverflow.com/questions/5537297/ios-how-to-perform-a-http-post-request –

0

这是一个干净而简单的方法。在您的xcode实现文件中创建一个像这样的方法:

注意:请记住根据您的需要对其进行自定义。重要的一点是传递名为“requestArray_”的请求数组。更改URL位http://localhost/test/index.php成你想要的网址

-(NSArray *) setRequestWithRequestArray:(NSArray *)requestArray_{ 
    NSError *error; 
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:requestArray_ 
                 options:NSJSONWritingPrettyPrinted error:&error]; 
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 

    NSString *post = [NSString stringWithFormat:@"requestArray=%@", jsonString]; 

    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO]; 

    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
    [request setURL:[NSURL URLWithString:@"http://localhost/test/index.php"]]; 
    [request setHTTPMethod:@"POST"]; 
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
    [request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"]; 
    [request setHTTPBody:postData]; 

    NSURLResponse *response; 
    NSError *errors = nil; 

    NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; 

    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:POSTReply options:0 error:&errors]; 

    NSLog(@"request %@", request); 
    NSLog(@"jsonArray%@",jsonArray); 

    return jsonArray; 
} 

而且在你的PHP创建一个测试方法是这样的:

$Array = $_POST["requestArray"]; 
function testMethod($Array){ 
     $get_result = array(); 
     $get_result = json_decode($Array); 

     foreach($get_result as $key1 => $value){ 
      $result = array(
        $key1 => $value, 
        $key1 => $value, 
        $key1 => $value, 
        $key1 => $value 
      ); 
     } 

     sendResponse(200, json_encode($result)); 
      return true; 
    } 
相关问题