带有 POST 的 NSURLConnection 不起作用 [英] NSURLConnection with POST doesn't work
本文介绍了带有 POST 的 NSURLConnection 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 POST 请求 URL 解析参数,但是 mypage.php 没有收到此参数...这是我的代码:
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
{
}
和 mypage.php
and mypage.php
if($_POST['name'] != "" && $_POST['email'] != "")
//Here the $_POST['name'] and the $_POST['email'] are empty...
推荐答案
试试这个:
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");
}
这篇关于带有 POST 的 NSURLConnection 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文