美文网首页iOS专题
iOS HTTP GET 请求

iOS HTTP GET 请求

作者: Zhen斌iOS | 来源:发表于2020-06-10 13:53 被阅读0次

    1、GET请求

    + (NSData* )doHttpGet:(NSString* )url {
        NSURL*uri=[NSURLURLWithString:url];
        NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL: uri];
        [request setHTTPMethod: @"GET"];
        NSData* returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
        return returnData;
    }
    

    2、Post请求1

    + (NSData* )doHttpPost:(NSString* )urlwithString: (NSString* )param {
        NSData*data=nil;
        if( param != nil && [param isEqualToString: @""] == NO) {
            param = [param stringByAddingPercentEscapesUsingEncoding: CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)];
            data=[param dataUsingEncoding: CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)];
        }
        return [self doHttpPost: url withParam: data];
    }
    
    + (NSData* )doHttpPost:(NSString *)url withParam:(NSData *)param {
        // 新建请求
        NSURL*uri = [NSURL URLWithString: url];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: uri cachePolicy: NSURLRequestReloadIgnoringLocalCacheData timeoutInterval: 40.0];
        // 设置请求参数
        [request setHTTPMethod: @"POST"];
        [request addValue: @"application/x-www-form-urlencoded" forHTTPHeaderField: @"Content-Type"];
        if(param!=nil)
            [request setHTTPBody: param];
        // 开发访问网络的状态提示
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: YES];
        // 请求连接
        NSError *error = nil;
        NSData *retData = [NSURLConnection sendSynchronousRequest: requestreturningResponse: nil error: nil];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: NO]; 
        // 返回结果
        return retData;
    

    希望对你有帮助!

    相关文章

      网友评论

        本文标题:iOS HTTP GET 请求

        本文链接:https://www.haomeiwen.com/subject/bqvutktx.html