18
編輯07/14AFNetworking - 如何使POST請求
正如比爾·伯吉斯在他回答的評論mentionned,這個問題是關係到AFNetworking
的version 1.3
。這裏的新手可能已經過時了。
我是很新的iPhone的發展,我使用AFNetworking作爲我的服務庫。
我查詢的API是REST風格的API,我需要發出POST請求。要做到這一點,我試着用下面的代碼:
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:@"my_username", @"username", @"my_password", @"password", nil];
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/login"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"Pass Response = %@", JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"Failed Response : %@", JSON);
}];
[operation start];
沒有與此代碼兩個主要問題:
AFJSONRequestOperation
似乎使一個GET
請求,而不是一個POST
一個。- 我不能把參數放到這個方法中。
我也試圖與此代碼:
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:@"my_username", @"username", @"my_password", @"password", nil];
NSURL *url = [NSURL URLWithString:@"http://localhost:8080"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
[httpClient postPath:@"/login" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Succes : %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failure : %@", error);
}];
有沒有更好的辦法,使我想在這裏把它做?
感謝您的幫助!
感謝您的回覆!只有一個問題:你的'SIOAPIClient'會在這裏成爲'MyAPIClient'嗎? –
你是對的...我從我自己的實現中複製/粘貼這個,並且改變了類名。我猜想錯過了一個地方。我編輯了我的答案,應該如何。 –
我試圖像你寫的那樣實現一個自定義客戶端,但是我得到一個錯誤:'沒有選擇器'sharedClient'的已知類方法。標題包含正確,所以我想知道爲什麼我得到這個錯誤。 –