objective-c 我可以从 iPhone 应用程序发出 POST 或 GET 请求吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/319463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 20:56:19  来源:igfitidea点击:

Can I make POST or GET requests from an iphone application?

iphoneobjective-ccocoa-touch

提问by Matt Gallagher

Is there a way using the iPhone SDK to get the same results as an HTTP POST or GET methods?

有没有办法使用 iPhone SDK 获得与 HTTP POST 或 GET 方法相同的结果?

回答by Matt Gallagher

Assume your class has a responseDatainstance variable, then:

假设你的类有一个responseData实例变量,那么:

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
}

This will send a GET. By the time the final method is called, responseDatawill contain the entire HTTP response (convert to string with [[NSString alloc] initWithData:encoding:].

这将发送一个 GET。到调用最终方法时,responseData将包含整个 HTTP 响应(使用 [[NSString alloc] initWithData:encoding:] 转换为字符串。

Alternately, for POST, replace the first block of code with:

或者,对于 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]];

回答by Ben Gottlieb

If you're using Objective C, you'll need to use the NSURL, NSURLRequest, and NURLConnection classes. Apple's NSURLRequest doc. HttpRequest is for JavaScript.

如果您使用目标 C,则需要使用 NSURL、NSURLRequest 和 NURLConnection 类。Apple 的 NSURLRequest 文档。HttpRequest 适用于 JavaScript。