iphone SDK:如何将数据发布到网址?

时间:2012-02-02 21:24:36

标签: objective-c http-post ios5

这可能是一个重复的问题,但我在搜索时找不到答案。那么,我如何将数据发布到网址?这是我到目前为止所得到的:

NSString *url = @"https://localhost/login.php";
NSURL *urlr = [NSURL URLWithString:url];
NSMutableURLRequest *urlre = [[NSMutableURLRequest alloc] init];


[urlre setURL:[NSURL URLWithString:url]];
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
NSString *user = [defs stringForKey:@"User"];
NSString *pass = [defs stringForKey:@"Pass"];
NSInteger *version = [defs integerForKey:@"Version"];


NSString *bodyData = [[NSString alloc] initWithFormat:@"user=%@&password=%@&version=%d",user,pass,version];
NSData *body = [bodyData dataUsingEncoding:NSASCIIStringEncoding];
NSURLResponse *response = nil;
NSError *error = nil;


[urlre setHTTPMethod:@"POST"];
[urlre setValue:[[NSString alloc] initWithFormat:@"%d",[body length]] forHTTPHeaderField:@"Content-Length"];
[urlre setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[urlre setHTTPBody:body];

NSData *dataThis = [NSURLConnection sendSynchronousRequest:urlre returningResponse:&response error:&error];

if(dataThis)
{
    NSLog(@"Connect Success");
} else {
    NSLog(@"%@",[error localizedDescription]);
}

以上是否正确?在我的

-(void) connection:(NSURLConnection*)connection didReceiveData:(NSData *)data

事件,我一无所获。即使在didFinishLoading中,它也不会对NSLog产生任何影响。请帮忙。

1 个答案:

答案 0 :(得分:0)

您是否为请求设置了代理人?

为什么不看一下像ASIHTTPRequest这样的框架,让事情变得如此简单。查看http://allseeing-i.com/ASIHTTPRequest/