How to do GET request via AFNetworking?
Asked Answered
E

5

10

I added directories AFNetworking and UIKit+AFNetworking to project manager. I use latest library 3.0.4

After I imported file AFNetworking.h in my class file .m. I found a lot examples how to make request to url, but information is old.

How to make GET request to URL and get data from server? Now function AFHTTPRequestOperation was removed.

This is first time working with libraries in xcode, I am beginner.

Eddy answered 6/1, 2016 at 17:33 Comment(1)
You don't need third-party libraries for that, check out NSURLSession.Asepsis
K
2
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://google.com/"]];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET"
                                                        path:@"http://google.com/api/pigs/"
                                                  parameters:nil];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    // Print the response body in text
    NSLog(@"Response: %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];
[operation start];

=============================================

You can also use AFHTTPRequestOperation:

NSOperationQueue *networkQueue = [[NSOperationQueue alloc] init];

networkQueue.maxConcurrentOperationCount = 5;

NSURL *url = [NSURL URLWithString:@"https://example.com"];

NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] 
initWithRequest:request];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {


    NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

    NSLog(@"%@", string);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    NSLog(@"%s: AFHTTPRequestOperation error: %@", __FUNCTION__, error);
}];
[networkQueue addOperation:operation];
Kab answered 6/1, 2016 at 17:49 Comment(4)
Thank you very much, but AFHTTPRequestOperation is not supportedEddy
Do you use only #import "AFNetworking.h"? Compilator does not see object AFHTTTPClientEddy
Note this solution is not functional in AFNetworking 3.0, see Chanchal's answer below for a working snippet.Pandolfi
Why is it necessary to initWithBaseUrl but then also provide the full path when using requestWithMethod?Edda
H
82

For AFNetworking 3.x:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:@"http://example.com/resources.json" parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];
Harmonicon answered 7/6, 2016 at 13:55 Comment(1)
The best answer as the questioner talks about AFNetworking 3.0+. The other above solutions are not supported by AFNetworking 3.0 anymore.Milfordmilhaud
K
2
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://google.com/"]];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET"
                                                        path:@"http://google.com/api/pigs/"
                                                  parameters:nil];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    // Print the response body in text
    NSLog(@"Response: %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];
[operation start];

=============================================

You can also use AFHTTPRequestOperation:

NSOperationQueue *networkQueue = [[NSOperationQueue alloc] init];

networkQueue.maxConcurrentOperationCount = 5;

NSURL *url = [NSURL URLWithString:@"https://example.com"];

NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] 
initWithRequest:request];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {


    NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

    NSLog(@"%@", string);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    NSLog(@"%s: AFHTTPRequestOperation error: %@", __FUNCTION__, error);
}];
[networkQueue addOperation:operation];
Kab answered 6/1, 2016 at 17:49 Comment(4)
Thank you very much, but AFHTTPRequestOperation is not supportedEddy
Do you use only #import "AFNetworking.h"? Compilator does not see object AFHTTTPClientEddy
Note this solution is not functional in AFNetworking 3.0, see Chanchal's answer below for a working snippet.Pandolfi
Why is it necessary to initWithBaseUrl but then also provide the full path when using requestWithMethod?Edda
L
1
please try below answer.
+(void)callAFWS:(NSDictionary *)dict withURL:(NSString *)strUrl 
withToken:(NSString *)strToken withBlock:(dictionary)block
{
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

[manager.requestSerializer setValue:strToken forHTTPHeaderField:@"Authorization"];

[manager GET:[NSString stringWithFormat:@"%@/%@",WebserviceUrl,strUrl] parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    if (!responseObject)
    {
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        [dict setObject:ServerResponceError forKey:@"error"];
        block(responseObject);
        return ;
    }
    block(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setObject:ServerResponceError forKey:@"error"];
    block(dict);
}];
}
Lowder answered 23/10, 2017 at 5:36 Comment(0)
R
-1

With AFNetworking 3.0 you need to make request as under:

NSURL * urlStr = [NSURL URLWithString:strURL];

NSDictionary *dictParameters = @{@"user[height]": height,@"user[weight]": weight};

AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];


[manager GET:url.absoluteString parameters:dictParameters success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"PLIST: %@", responseObject);

} failure:^(NSURLSessionTask *operation, NSError *error) {
    NSLog(@"Error: %@", error);

}];
Rangefinder answered 2/3, 2016 at 6:46 Comment(0)
K
-1
(void)postDatabyAF{

NSString *url;

NSDictionary *dict;

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

manager.responseSerializer = [AFJSONResponseSerializer serializer];

manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:
                              NSJSONReadingAllowFragments];

[manager POST:url parameters:dict success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {

    NSLog(@" operation.responseData  %@",operation.responseData);
    NSLog(@" operation.response %@",operation.response);
    NSLog(@"statusCode %ld",operation.response.statusCode);

} failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {

    if (error) {

    }
    else{


    }
}];

}

Kowtko answered 14/12, 2016 at 21:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.