2010-05-17 184 views
0

我想知道为什么这个HTTP POST请求不能在我的iPhone应用程序中工作。HTTP POST请求不起作用,委托方法不被调用

我知道这个URL是正确的,而且我发送的变量是正确的,但由于某种原因,请求没有被.aspx页面收到。

编辑:

我重构代码到自己的类,有自己的委托方法。但委托方法没有被调用。

类被称为是这样的:

URLCallClass *reporter=[[[URLCallClass alloc] init]autorelease]; 
    [reporter sendoview:@"http://mysite/page.aspx" params:httpBodyString]; 

,这是实际的类本身:

-(void)sendview:(NSString *)server params:(NSString *)params 
{ 

    NSURL* url=[[NSURL alloc] initWithString:server]; 
    NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url]; 
    [url release]; 

    [urlRequest setHTTPMethod:@"POST"]; 
    [urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]]; 

    connectionResponse=[[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self] autorelease]; 
    //NSURLConnection *connectionResponse = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self]; 


    if (!connectionResponse) 
    { 
     NSLog(@"Failed to submit request"); 
    } 
    else 
    { 
     NSLog(@"---------Report Request submitted ---------"); 
    } 
} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    NSLog(@"report received response"); 

} 

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

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
    NSLog(@"report failed with error"); 
    NSLog(@"%@", [error description]); 
} 
- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    NSLog(@"Promo View Reported"); 
} 

-(void)dealloc 

{ 
    [connectionResponse release]; 

    [super dealloc]; 

} 

回答

0

事实证明它与线程

NSURLConnection delegation and threading - iPhone

我用这个解决方案做

http://www.depl0y.com/?p=345

+0

所以澄清:所有这些代码运行在主线程以外的线程? – JeremyP 2010-05-18 15:35:06

+0

那么在主线程中有UIView正在运行,并且httprequest代码是在此UIView中的类的实例中。我相信这个http请求类在完成它的异步urlconnection之前退出,一旦调用它的父UIView函数完成执行调用它的方法。 所以我不认为它是在主线程上,但叫它的类是。 虽然我可以离开这里,但对我来说这是相当新的,我仍然在学习。 – dubbeat 2010-05-19 08:44:16

2

您应该实现连接:didFailWithError:在委托。

​​会告诉你,究竟发生了什么错误。

+0

的didfailWithError处理程序不会被调用 – dubbeat 2010-05-17 15:15:36

0

您的url实际上是否正在创建?如果有任何问题,NSURLs initWithString:方法将返回nil

+0

我评论了我所有的代码除有问题的代码,它的工作发现。我在同一个类中使用另一个NSURLConnection。它在这之前被执行。这可能会以某种方式造成问题吗? – dubbeat 2010-05-18 07:38:22

+0

网址被成功创建 – dubbeat 2010-05-18 10:21:40

0

你打印响应头吗?我建议你实现几乎每个委托方法来检查你的连接实际发生了什么,首先尝试打印didReceiveResponse方法,以及使用连接接收的一些数据:didReceiveData方法。

也许您的数据的编码是服务器无法处理的东西,请尝试使用NSUTF8StringEncoding而不是NSISOLatin1StringEncoding作为正文编码。