我习惯使用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,我转移到AFNetworking
API。
但是,当从逻辑移动到另一个不同时,它有点令人困惑,我想知道如何使用AFNetworking
传递相同的请求。
提前完成。
答案 0 :(得分: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);
}];
答案 1 :(得分:-2)
我刚开始使用AFNetworking
。经过一番摔跤(和一个愚蠢的错误)后,我能够让下面的POST例程发布并与userName一起成像。
有一件事 - 不知道是否需要 - 但我初始化并保留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];
}