2013-12-06 1 views
4

это фрагмент кода, который я отправляю на PHP-страницу, но когда я делаю print_r ($ _ POST); я получаю пустой массив, но когда я делаю print_r ($ _ GET), я получаю переменную, которую я использую, чтобы опубликовать данные, то есть , имя, но оно также пустое, может ли кто-нибудь разобраться, что я делаю неправильно здесьне может получить данные как сообщение при отправке его в качестве сообщения из IOS NSMutableURLRequest

#import "ViewController.h" 

@interface ViewController() 

@end 

@implementation ViewController 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

- (IBAction)btnFetchData1:(id)sender { 
// NSString *urlString = [NSString stringWithFormat:@"http://localhost/adi/adnan.php?name=%@", [self.txtName text]]; 
     NSString *urlString = [NSString stringWithFormat:@"http://localhost/adi/adnan.php"]; 
    NSString *post = [NSString stringWithFormat:@"name=%@",@"adnan"]; 
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
    NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]]; 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
    [request setURL:[NSURL URLWithString:urlString]]; 
    [request setHTTPMethod:@"POST"]; 
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
    [request setHTTPBody:postData]; 

    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
delegate:self]; 
    if (conn) { 
     _receivedData=[NSMutableData data]; 
    } else { 
     //something bad happened 
    } 
} 

#pragma NSUrlConnectionDelegate Methods 

-(void)connection:(NSConnection*)conn didReceiveResponse:(NSURLResponse *)response 
{ 
    if (_receivedData == NULL) { 
     _receivedData = [[NSMutableData alloc] init]; 
    } 
    [_receivedData setLength:0]; 
    NSLog(@"didReceiveResponse: responseData length:(%d)", _receivedData.length); 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    [_receivedData appendData:data]; 
} 


- (void)connection:(NSURLConnection *)connection 
    didFailWithError:(NSError *)error { 
    NSLog(@"Connection failed! Error - %@ %@", 
      [error localizedDescription], 
      [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    NSLog(@"Succeeded! Received %d bytes of data",[_receivedData length]); 

    NSString *responseText = [[NSString alloc] initWithData:_receivedData encoding: NSASCIIStringEncoding]; 
    NSLog(@"Response: %@", responseText); 

    NSString *newLineStr = @"\n"; 
    responseText = [responseText stringByReplacingOccurrencesOfString:@"<br />" withString:newLineStr]; 

    [self.lblData setText:responseText]; 
} 

ответ

0

Вы создали postLength, но никогда не использовал его, не пробуйте это может решить:

//create URL for the request 
NSString *urlString = [NSString stringWithFormat:@"http://localhost/adi/adnan.php"]; 

//Post data 
NSString *post = [NSString stringWithFormat:@"name=%@",@"adnan"]; 
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding] 
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]]; 

//the request 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 

//Bind the request with Post data 
[request setURL:[NSURL URLWithString:urlString]]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
[request setHTTPBody:postData]; 
+0

до сих пор никаких изменений. Я все еще могу получить данные через print_r ($ _ GET), но не print_r ($ _ POST) –

+0

см. Мое обновление, избегая кодирования ASCII, если вы можете, вы не хотите рисковать. кроме этого я не вижу других проблем с вашим кодом, вы уверены, что проблема не на сервере PHP? – meda

 Смежные вопросы

  • Нет связанных вопросов^_^