POST和PUT请求AFNetworking

我正在尝试打电话给服务器。 GET调用工作得很好,并返回正确的JSON,但是当我尝试做PUT或POST时,服务器返回一个错误。

我将服务器设置为接收下一条消息:

method POST curl -X POST -d "number=NUMBER&name=NAME&lat=32.5713&lon=60.3926" http://server.com/users/ method PUT curl -X PUT -d "number=USER&name=NAME6&lat=-34.5552&lon=32.3333" http://server.com/users/ 

我怎样才能用这两种方法调用服务器?

我会为所有请求创build一个APIClient类,而不是每次发出请求时创build一个新客户端。

请参阅: https : //github.com/AFNetworking/AFNetworking/tree/master/Example/Classes AFTwitterAPIClient.h&AFTwitterAPIClient.m

但基于你的问题。 我相信代码会看起来像这样。 (代码未经testing)

 NSURL *url = [NSURL URLWithString:@"http://server.com"]; AFHTTPClient *client = [[AFHTTPClient alloc]initWithBaseURL:url]; //depending on what kind of response you expect.. change it if you expect XML [client registerHTTPOperationClass:[AFJSONRequestOperation class]]; NSDictionary *params = [[NSDictionary alloc]initWithObjectsAndKeys: @"NUMBER",@"number", @"NAME",@"name", @"32.5713",@"lat", @"60.3926",@"lon", nil]; [client putPath:@"users" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"success"); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"failure"); }]; 

至于发布请求..只是使用postPath而不是putPath,它会正常工作。 🙂

希望我帮了忙。

问候,

Steve0hh

由于没有关联的代码,我假设你使用getPath:parameters:success:failure:或者没有parameters发送POST请求,这可能是你的服务器/ API所要求的。

 postPath:parameters:success:failure: putPath:parameters:success:failure: 

同时参考AFNetworking Post Request请求示例代码和带有AFnetworking的POST