HTTP Post方法php和ios

时间:2013-04-17 10:28:27

标签: iphone http-post

我面临一个大问题,

我想将数据发送到我的服务器,我的数据是一个字符串。

我不想使用Get方法,因为字符串可能很长,所以我想使用POST方法,但一切顺利,错误,如果有人可以帮助我,他将成为我的英雄:)

这是我的php代码:

<?php include("config.inc.php");
if (isset($_POST['contentInterro']) && $_POST['contentInterro'] !="" ) {
//$id_user = $_POST['contentInterro'];
//$db->sql_query("INSERT INTO interrogations VALUES(DEFAULT, '$id_user')");
echo "succes";
}else{
echo "This is an error";
}

?>

这是我的应用代码:

 NSData *postData = [stringToPost2 dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];


    NSMutableURLRequest *requestPost = [[NSMutableURLRequest alloc] init];

    NSURL *urlPost = [NSURL URLWithString:@"http://buzznapps.fr/FDF/postInterrogation.php"];

    [requestPost setURL:urlPost];
    [requestPost setHTTPMethod:@"POST"];
    [requestPost setValue:@"lol" forHTTPHeaderField:@"contentInterro"]; 



    NSError *errorURL;
    NSURLResponse *response;
    NSData *urlData = [NSURLConnection sendSynchronousRequest:requestPost returningResponse:&response error:&errorURL];

    NSString *str = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];

    NSLog(@"Str = %@",str); 

我总是收到错误,我在网上搜索我不知道如何获取这些数据! 谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

    #define TIMEOUT_INTERVAL 60
    #define CONTENT_TYPE @"Content-Type"
    #define URL_ENCODED @"application/x-www-form-urlencoded"
    #define GET @"GET"
    #define POST @"POST"

     -(NSMutableURLRequest*)getNSMutableURLRequestUsingGetMethodWithUrl:(NSString*)url
        {
            NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:TIMEOUT_INTERVAL];
            [req setHTTPMethod:GET];
            return req;
        }

        -(NSMutableURLRequest*)getNSMutableURLRequestUsingPOSTMethodWithUrl:(NSString *)url postData:(NSString*)_postData
        {
            NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:TIMEOUT_INTERVAL];
            [req setHTTPMethod:POST];
            [req addValue:URL_ENCODED forHTTPHeaderField:CONTENT_TYPE];
            [req setHTTPBody: [_postData dataUsingEncoding:NSUTF8StringEncoding]];
            return req;
        }

@try
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSString *_postData = [NSString stringWithFormat:@"user_name=%@&password=%@",@"user_name",@"password"];
    NSMutableURLRequest *req = [self getNSMutableURLRequestUsingPOSTMethodWithUrl:_url postData:_postData];
   [NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         if (error)
         {
             [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
             NSLog(@"error==%@==",[error localizedDescription]);
         }
         else
         {
             NSError *errorInJsonParsing;
             NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorInJsonParsing];

             if(errorInJsonParsing) //error parsing in json
             {
                 [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                 NSLog(@"error in json==%@==",[error localizedDescription]);
             }
             else
             {
                 //do some operations
             }
         }
     }];
}
@catch(NSException *exception)
{
    NSLog(@"error in exception==%@==",[exception description]);
}



same way it works for the get method, just call the 

NSMutableURLRequest *req = [self getNSMutableURLRequestUsingGetMethodWithUrl:_url];代替NSMutableURLRequest *req = [self getNSMutableURLRequestUsingPOSTMethodWithUrl:_url postData:_postData];