iOS开发人员提到访问HTTP接口,好像不用AFNetwork就不是政治正确,但结合开发历程来看,其实好多时候,我们只是简单访问HTTP API接口,一个方法就搞定了,不用引用那么庞大的库,正应了那句,杀鸡何须用牛刀。
+(void)rawGet:(NSString*)url callback:(void (^)(int httpCode,NSString* response))callback{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSURL *urlObj = [NSURL URLWithString:url];
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
request.URL = urlObj;
request.HTTPMethod = @"GET";
request.timeoutInterval = 10;
int httpCode = 200;
NSError* httpError = nil;
NSURLResponse *response = nil;
NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&httpError];
if(httpError){
if(response != nil && [response isKindOfClass:[NSHTTPURLResponse class]]){
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
httpCode = (int)httpResponse.statusCode;
}else{
httpCode = -1;
}
}
if(callback){
if(httpCode == 200){
NSString* response = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
callback(httpCode,response);
}else{
callback(httpCode,nil);
}
}
});
}
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8