我正在对 Web 服务进行同步调用,有时我会从 Web 服务返回正确的结果,有时我会收到指示运行时错误的 HTML 结果。在 iOS 端我必须做些什么才能正确调用网络服务。这是我的代码:
NSURLResponse *response = nil;
NSError *error = nil;
NSString *requestString = @"some parameters!";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
NSString *responseData = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
是不是我发布不当?
最佳答案
你必须像这样设置 urlconnection 的委托(delegate)方法
NSMutableURLRequest* urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
[urlRequest setHTTPMethod:@"POST"];
urLConnection=[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
下面的委托(delegate)方法可以解决问题
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
[receivedData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
如果连接失败,您将在以下委托(delegate)中收到错误
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{}
你最好从已完成的连接中得到响应,它告诉你所有数据都已收到
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
recievedData //the complete data
}
关于ios - URLConnection sendSynchronousRequest 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7435537/