这是我第一次通过HTTP请求处理服务器通信,为了确定我正在做什么,并且“我手中有问题”我想打印服务器应该的xml文件还给我。 如果有人可以帮助我,请:
这是我的代码:
(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if ([stories count] == 0) {
NSString * l_api_key = @"********************************************";
NSString * l_secret_key = @"******************************************";
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:[@myURLHERE stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60.0];
[theRequest setHTTPMethod:@"POST"];
[theRequest setValue:@"application/xml" forHTTPHeaderField:@"Accept"];
[theRequest setValue:@"application/x-www-form-unrlencoded" forHTTPHeaderField: @"Content-Type"];
[theRequest addValue:l_api_key forHTTPHeaderField: @"EMApikey"];
[theRequest addValue:[self hmacsha1:l_api_key secret:l_secret_key] forHTTPHeaderField: @"EMRequestHash"];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
NSLog(@"%@", theConnection);
if( theConnection )
{
NSData *webData = [[NSMutableData data] retain];
NSLog(@"%@", webData);
//[self parseXMLFileAtURL:path];
}
else
{
NSLog(@"theConnection is NULL");
}
[theConnection release];
}
cellSize = CGSizeMake([newsTable bounds].size.width, 60);
}
答案 0 :(得分:1)
您需要发送POST请求并获取响应,请参阅以下示例:
//create the body
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[[NSString stringWithFormat:@"<xml>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"<yourcode/>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"</xml>"] dataUsingEncoding:NSUTF8StringEncoding]];
//post
[theRequest setHTTPBody:postBody];
//get response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"Response Code: %d", [urlResponse statusCode]);
if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) {
NSLog(@"Response: %@", result);
//here you get the response
}
答案 1 :(得分:1)
[NSURLConnection sendAsynchronousRequest:theRequest
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(@"%@", [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]);
}];
比以下更方便:
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];