【问题标题】:Post request with AFNetworking使用 AFNetworking 发布请求
【发布时间】:2012-09-29 05:34:49
【问题描述】:

我是编程新手,尤其是网络方面。所以现在我正在创建应用程序来与 Instagram 进行交互。在我的项目中,我使用 AFNetworking。我在这里看到了他们的文档和许多示例。而且我还不明白如何获得对 Instagram API 的 POST 请求。请你能给我真实的代码示例或我可以阅读有关如何执行此操作的内容吗?请帮忙。我试图提出这样的请求,它没有错误也没有响应。它什么也没给:(

(IBAction)doRequest:(id)sender{

NSURL *baseURL = [NSURL URLWithString:@"http://api.instagram.com/"];

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[httpClient defaultValueForHeader:@"Accept"];

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                        user_token, @"access_token",
                        nil];

[httpClient postPath:@"/feed" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
    // reponseObject will hold the data returned by the server.
    NSLog(@"data: %@", responseObject);
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error retrieving data: %@", error);
}];


NSLog(@"click!!");
}

【问题讨论】:

    标签: iphone ios afnetworking


    【解决方案1】:

    很少需要关心的事情。 Instagram API 返回 JSON,因此您可以使用 AFJSONRequestOperation,它将返回已解析的 NSDictionary。
    Instagram API 说:

    所有端点只能通过 https 访问,并且位于 api.instagram.com.

    您应该更改您的 baseURL。

    AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:yourURL];
    NSURLRequest *request = [client requestWithMethod:@"POST"
                                                 path:@"/your/path"
                                           parameters:yourParamsDictionary];
    AFJSONRequestOperation *operation =
    [AFJSONRequestOperation
     JSONRequestOperationWithRequest:request
     success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
    {
        // Do something with JSON
    }
     failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)
    {
        // 
    }];
    
    // you can either start your operation like this 
    [operation start];
    
    // or enqueue it in the client default operations queue.
    [client enqueueHTTPRequestOperation:operation];
    

    【讨论】:

    • 非常感谢,弗洛里安!当我靠近我的mac时,我会试试看。还有一件事:在请求参数“路径”中——它是设备上的 json 路径还是本地路径?
    • 它是附加到您提供给 AFHTTPClient 的基本 URL 的路径。例如,通过为路径指定“/users/self/feed”,请求 URL 将为https://api.instagram.com/users/self/feed
    猜你喜欢
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多