NSURLConnection with POST doesn't work

梦想与她 提交于 2019-12-14 03:29:43

问题


I'm trying request a URL parsing parameters with POST, but mypage.php is not receiving this parameters... Here is my code:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://myurl/mypage.php"]];
NSString *params = [[NSString alloc]initWithFormat:@"name=%@&surname=%@&location=%@&email=%@&password=%@&gender=%@&tipo=%@", name, surname, location, email, password, gender, tipo];                   
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(params);
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) {
    webData = [[NSMutableData data] retain];
}
else
{
}

and mypage.php

if($_POST['name'] != "" && $_POST['email'] != "") 
//Here the $_POST['name'] and the $_POST['email'] are empty...

回答1:


You're not starting the connection. You should do it with a [conn start];




回答2:


Try this:

NSString *params=[NSString stringWithFormat:@"name=%@&surname=%@&location=%@&email=%@&password=%@&gender=%@&tipo=%@", name, surname, location, email, password, gender, tipo];
NSData *postData=[params dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:@"http://myurl/mypage.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
[request setValue:[NSString stringWithFormat:@"%i",postData.length] forHTTPHeaderField:@"Content-Length"];  

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (data!=nil) {
   NSString *output=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
   NSLog(@"output: %@", output);
}else{
   NSLog(@"data is empty");
}


来源:https://stackoverflow.com/questions/16861504/nsurlconnection-with-post-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!