【问题标题】:Can I make POST or GET requests from an iphone application?我可以从 iphone 应用程序发出 POST 或 GET 请求吗?
【发布时间】:2012-09-11 16:17:12
【问题描述】:

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

【问题讨论】:

    标签: iphone objective-c cocoa-touch


    【解决方案1】:

    假设你的类有一个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]];
    

    【讨论】:

    • 我在这里发布了一个后续问题:stackoverflow.com/questions/431826/…(我认为它值得自己提出问题。)
    • 一定要检查 [[NSURLConnection alloc] initWithRequest:request delegate:self];要求零回报。
    【解决方案2】:

    如果您使用的是 Objective C,则需要使用 NSURL、NSURLRequest 和 NURLConnection 类。 Apple's NSURLRequest doc。 HttpRequest 用于 JavaScript。

    【讨论】:

      猜你喜欢
      • 2012-09-22
      • 1970-01-01
      • 2023-03-17
      • 2016-11-27
      • 1970-01-01
      • 2011-02-28
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      相关资源
      最近更新 更多