在iOS上从ASIHTTPRequest转换为AFNetworking

时间:2012-07-02 13:50:45

标签: ios asihttprequest afnetworking

我想要做的是将json文件发布到我的服务器。我终于使用ASIHTTPRequest做了那个,我的代码是:

NSURL *url = [NSURL URLWithString:@"http://foo.foo.foo"];
            ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
            [request setRequestMethod:@"PUT"];

            [request addRequestHeader:@"Authorization" value:@"Basic dslfkdsfdsflsdkfslkgflksflksdlfkg"]; 
            [request addRequestHeader:@"Content-Type" value:@"application/json; charset=utf-8"];


            [request appendPostData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]]; 
            [request startSynchronous];

            NSLog(@"%@", [request responseString]);   

我现在需要的是将上述代码翻译成AFNetworking。有任何想法吗?? 感谢您阅读我的帖子:))

1 个答案:

答案 0 :(得分:3)

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://foo.foo.foo"]];
client.parameterEncoding = AFJSONParameterEncoding;
[client registerHTTPOperationClass:[AFJSONRequestionOperation class]];
[client setAuthorizationHeaderWithUsername:... password:...];
[client putPath:@"/path/to/resource" parameters:(_your JSON object as a dictionary_) 
            success:^(AFHTTPRequestOperation *operation, id responseObject) {
              NSLog(@"%@", [request responseString]);
          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              NSLog(@"Error: %@", error);
          }];