본문 바로가기

iPhone dev./AFNetworking / ASIHTTP

AFNetworking POST 요청 보내기

참고 사이트: http://stackoverflow.com/questions/7623275/afnetworking-post-request


This isn't the only way to do it, but requestWithMethod: is one way to do it:

NSURL *url = [NSURL URLWithString:@"https://mysite.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                        height, @"user[height]",
                        weight, @"user[weight]",
                        nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"/myobject" parameters:params];

AFHTTPRequestOperation *operation = [AFHTTPRequestOperation operationWithRequest:request
                                     completion:^(NSURLRequest *req, NSHTTPURLResponse *response, NSData *data, NSError *error) {
    BOOL HTTPStatusCodeIsAcceptable = [[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)] containsIndex:[response statusCode]];
    if (HTTPStatusCodeIsAcceptable) {
        NSLog(@"Request Successful");
    } else {
        NSLog(@"[Error]: (%@ %@) %@", [request HTTPMethod], [[request URL] relativePath], error);
    }
}];

NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
share|improve this answer

혹은 다음을 참고한다:
http://samwize.com/2012/10/25/simple-get-post-afnetworking/


Simple GET/POST AFNetworking

 | COMMENTS

AFNetworking is the choice for iOS/Mac developers when it comes to choosing a HTTP library.

ASIHTTPRequest used to be the choice, until 2011 when it became inactive.

I am one of the many who is forced to switch camp.

In many ways, it seems AFNetworking would be better. It uses blocks!

However, I find the documentation lacking. It has an overviewgetting startedintroductioncomplete reference, … But yet, it didn’t provide example on how you make a simple HTTP GET or POST.

Here is how you do it:

GET

1
2
3
4
5
6
7
8
9
10
11
12
13
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://samwize.com/"]];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET"
                                                        path:@"http://samwize.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];

POST

POST a urlencoded form name=piggy in the http body.

1
2
3
4
5
6
7
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://samwize.com/"]];
[httpClient setParameterEncoding:AFFormURLParameterEncoding];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
                                                        path:@"http://samwize.com/api/pig/"
                                                  parameters:@{@"name":@"piggy"}];

// Similar to GET code ...

If you want to POST a json such as {"name":"piggy"}, you change the encoding:

1
[httpClient setParameterEncoding:AFJSONParameterEncoding];

If you want to do a multi-part POST of an image, you do this:

1
2
3
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"http://samwize.com/api/pig/photo" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
}];

This simple guide has been helped by thisthis and this.

Pitfalls

Do not use [[AFHTTPClient alloc] init], as that does not initialize a lot of stuff. Use initWithBaseURL instead.

For instance, if in the above example (POST JSON) you had used init, the Content-Type will be

application/json; charset=(null) 

Charset should be utf-8, not null

Thank you very much Joseph it worked very well. I just had a question after I alloc the httpClient I release it after creating the request, I dont seem to have any crashes and seems to work well. I just wanted to confirm that that is the correct spot to release it. Thank you very much again. Kind Regards – Sam Barnet Oct 2 '11 at 20:13
1 
Yes, that would works. The AFHTTPClient is really intended to be kept around and used again if you make another request, but releasing it straight after the 'requestWithMethod:' call is acceptable. – JosephH Oct 2 '11 at 21:22
Hi Joseph, I finally got it working with a json response and I set up another questionstackoverflow.com/questions/7630289/… to really know whether I am doing it right. Thanks so much sorry to bother. – Sam Barnet Oct 3 '11 at 1:05
7 
This code sample makes me want to keep using ASI. – Jason Moore Feb 16 at 14:35
hey sorry to make this out of the blue but I have been looking everywhere on what to import however, it just doesnt do it for me I have imported #import "AFHTTPRequestOperation.h" #import "AFHTTPClient.h" #import "ASIHTTPRequest.h" #import "ASIFormDataRequest.h" #import <Foundation/Foundation.h> yet it still doesnt work :( – chaitanya.varanasi Jul 12 at 14:51


'iPhone dev. > AFNetworking / ASIHTTP' 카테고리의 다른 글

AFNetworking 기초  (0) 2012.11.26
ASIHTTP를 이용한 request/response  (0) 2011.08.08