0

我用来工作ASIHTTPRequest

NSURL *url = [NSURL URLWithString:@"http://data.mywebsite/api/views/INLINE/rows.json?method=index"];

    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    request.requestMethod = @"POST";    
    [request addRequestHeader:@"Content-Type" value:@"application/json"];
    [request appendPostData:[json dataUsingEncoding:NSUTF8StringEncoding]];

    [request setDelegate:self];
    [request setCompletionBlock:^{        
        NSString *responseString = [request responseString];
        NSLog(@"Response: %@", responseString);
    }];
    [request setFailedBlock:^{
        NSError *error = [request error];
        NSLog(@"Error: %@", error.localizedDescription);
    }];

    [request startAsynchronous];

由于不再维护 ASIHTTPRequest,我转向AFNetworkingAPI。但是,从一个逻辑转移到另一个不同的逻辑时有点令人困惑,我想知道如何使用AFNetworking.

提前谢谢。

4

2 回答 2

1
NSURL *url = [NSURL URLWithString:@"http://data.mywebsite/api"];   
AFHTTPClient *client = [[[AFHTTPClient alloc] initWithBaseURL:url];
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client postPath:@"views/INLINE/rows.json?method=index"
      parameters:json
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
           NSLog(@"Response: %@", operation.responseString);
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
           NSLog(@"Error: %@", error);
}];
于 2012-03-29T19:21:06.647 回答
-2

我也刚开始AFNetworking。经过一番挣扎(和一个愚蠢的错误),我能够让下面的 POST 例程与用户名一起发布和图像。

一件事-不知道是否需要-但我初始化并保留了一个实例AFHTTPClient。还要创建一个NSOperationQueue实例来管理请求。

无论如何-希望下面的代码有用。它对我有用。

// 属性初始化viewDidLoad

 client = [[AFHTTPClient alloc ]initWithBaseURL: [NSURL URLWithString:@"http://example.com/test/"]];

// 方法

- (void)test
{

UIImage * img = [self.paintingView  snapUIImage];
NSData *imageData = UIImageJPEGRepresentation(img, .5);

NSMutableDictionary * lParameters = [NSMutableDictionary dictionary];
[lParameters setObject:@"binky" forKey:@"user"];

NSMutableURLRequest *myRequest = 
[client multipartFormRequestWithMethod:@"POST" 
                                    path:@"loader.php"
                            parameters:lParameters 
             constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
                     [formData appendPartWithFileData:imageData name:@"userfile" fileName:@"image.jpg" mimeType:@"images/jpg"];
                 }];

[myRequest setTimeoutInterval: 5];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:myRequest];
[operation setUploadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {

    NSLog(@"Sent %d of %d bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];

[operation setCompletionBlock:^{
    NSLog(@"%@", operation.responseString); //Lets us know the result including failures

}];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:operation];

}

于 2012-03-17T21:58:39.913 回答