我可以从iphone应用程序发出POST或GET请求吗? [英] Can I make POST or GET requests from an iphone application?
本文介绍了我可以从iphone应用程序发出POST或GET请求吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法使用iPhone SDK获得与HTTP POST或GET方法相同的结果?
Is there a way using the iPhone SDK to get the same results as an HTTP POST or GET methods?
推荐答案
假设您的类有一个 responseData
实例变量, / p>
Assume your class has a responseData
instance variable, then:
responseData = [[NSMutableData data] retain];
NSURLRequest *request =
[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.domain.com/path"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
然后将以下方法添加到您的类中:
And then add the following methods to your class:
- (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:]的字符串。
This will send a GET. By the time the final method is called, responseData
will contain the entire HTTP response (convert to string with [[NSString alloc] initWithData:encoding:].
或者,对于POST,将第一个代码块替换为:
Alternately, for POST, replace the first block of code with:
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.domain.com/path"]];
[request setHTTPMethod:@"POST"];
NSString *postString = @"Some post string";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
这篇关于我可以从iphone应用程序发出POST或GET请求吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文