有没有办法使用 iPhone SDK 获得与 HTTP POST 或 GET 方法相同的结果?
假设你的班级有一个responseData
实例变量,则:
responseData = [[NSMutableData data] retain];
NSURLRequest *request =
[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.domain.com/path"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
然后将以下方法添加到您的类中:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// Show error
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// Once this method is invoked, "responseData" contains the complete result
}
这将发送一个 GET。当调用最终方法时,responseData
将包含整个 HTTP 响应(使用 [[NSString alloc] initWithData:encoding:] 转换为字符串。
或者,对于 POST,将第一块代码替换为:
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.domain.com/path"]];
[request setHTTPMethod:@"POST"];
NSString *postString = @"Some post string";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)