ANRestOps 是一个基于 NSURLConnection 和 NSOperationQueue API 的简单库。它抽象了大部分设置这些对象复杂性,并允许您用一行代码执行简单的 REST 调用。
ANRestOps 目前有 GET、POST、PUT 和 DELETE 方法。方法调用将返回一个 ANRestOpsResponse
实例。该类提供多个辅助方法来从响应中提取数据。请参阅 ANRestOpsResponse.h
。
以下是如何执行 GET
请求的示例:
ANRestOpsResponse *response = [ANRestOps get:@"http://httpbin.org/get"];
或者,您可以可选地以 NSDictionary
的形式包含参数。键和值将在请求之前格式化为网页表单(application/x-www-form-urlencoded
)。
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:@"Value1",@"Key1",@"Value2",@"Key2", nil];
ANRestOpsResponse *response = [ANRestOps get:@"http://httpbin.org/get" withParameters:params];
要后台执行 GET
请求,可以使用以下方法:
[ANRestOps getInBackground:@"http://httpbin.org/get"
beforeRequest:^
{
// Put any work that needs to be done before the request here
}
onCompletion:^(ANRestOpsResponse *response)
{
// The completion handler will be passed the response and is run on the main thread
}];
或者可选地添加参数:
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:@"Value1",@"Key1",@"Value2",@"Key2", nil];
[ANRestOps getInBackground:@"http://httpbin.org/get"
parameters:params
beforeRequest:^
{
// Put any work that needs to be done before the request here
}
onCompletion:^(ANRestOpsResponse *response)
{
// The completion handler will be passed the response and is run on the main thread
}];
POST
请求也可以以此类推。有一个额外选项允许您选择如何格式化有效负载。您可以传递一个 NSString
实例或一个 NSDictionary
,并选择是否将其格式化为表单参数或 JSON。下面是一个示例。与 GET
类似,POST
请求可以是同步的也可以是异步的。
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:@"Value1",@"Key1",@"Value2",@"Key2", nil];
[ANRestOps postInBackground:@"http://httpbin.org/get"
payload:params
payloadFormat:ANRestOpsJSONFormat
beforeRequest:^
{
// Put any work that needs to be done before the request here
}
onCompletion:^(ANRestOpsResponse *response)
{
// The completion handler will be passed the response and is run on the main thread
}];
ANRestOps 至少需要 iOS 7 和 ARC。
Ayush Newatia,[email protected]
ANRestOps 可在 MIT 许可证下使用。请参阅 LICENSE 文件以获取更多信息。