如何在Xcode上使用HTTP POST

时间:2013-07-31 16:11:06

标签: ios http http-post

很抱歉,这里有初学者问题。我正在尝试使用HTTP post从URL中检索XML文档,并且我需要在POST请求中包含一些参数。我从{{3}获得了代码在Objective C部分,我开始理解它。但我现在需要尝试做的是在我的应用程序中使用该类。以下是我需要包含的参数:

URL: https://admin.poslavu.com/cp/reqserv/ 
dataname=tangere_techno&key=dBkeY&token=dBt0kEn&table=menu_groups



1 个答案:

答案 0 :(得分:4)

尝试:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://admin.poslavu.com/cp/reqserv/"]];
[request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
[request setHTTPBody:[[NSString stringWithFormat:@"dataname=tangere_techno&key=dBkeY&token=dBt0kEn&table=menu_groups"] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:@"POST"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error) {
    NSLog(@"Error:%@", error.localizedDescription);
}
else {
    //success
}

数据应该是您的XML信息,但您首先需要解析它。您应该尝试查看Apple的文档以获取更多信息。如果您尝试以异步方式发出请求,请尝试以下操作:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://admin.poslavu.com/cp/reqserv/"]];
[request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
[request setHTTPBody:[[NSString stringWithFormat:@"dataname=tangere_techno&key=dBkeY&token=dBt0kEn&table=menu_groups"] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:@"POST"];


AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:req];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
    NSData *data = (NSData *)responseObject;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];
[operation start];