iOS不依靠AFNetwork訪問HTTP

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);
            }
        }
    });
}

所屬標簽

無標簽

25选5玩法中奖