我可以从iphone应用程序发出POST或GET请求吗?

26 iphone cocoa-touch objective-c

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

Mat*_*her 45

假设您的类有一个responseData实例变量,然后:

responseData = [[NSMutableData data] retain];

NSURLRequest *request =
    [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.domain.com/path"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
Run Code Online (Sandbox Code Playgroud)

然后将以下方法添加到您的类:

- (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
}
Run Code Online (Sandbox Code Playgroud)

这将发送一个GET.到调用final方法时,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]];
Run Code Online (Sandbox Code Playgroud)


Ben*_*ieb 8

如果您使用的是Objective C,则需要使用NSURL,NSURLRequest和NURLConnection类.Apple的NSURLRequest doc.HttpRequest适用于JavaScript.