IOS获取request.HTTPBodyStream中请求体内容,NSInputStream读到NSData

1、NSMutableURLRequest请求中,请求体有HTTPBody和HTTPBodyStream两种,这两者是互斥的(如下):

/*!
    @abstract Sets the request body data of the receiver.
    @discussion This data is sent as the message body of the request, as
    in done in an HTTP POST request.
*/
@property (nullable, copy) NSData *HTTPBody;
/*!
    @abstract Sets the request body to be the contents of the given stream. 
    @discussion The provided stream should be unopened; the request will take
    over the stream's delegate.  The entire stream's contents will be 
    transmitted as the HTTP body of the request.  Note that the body stream
    and the body data (set by setHTTPBody:, above) are mutually exclusive 
    ( body stream和 body data是互斥的)
    - setting one will clear the other.
   ( 设置其中一个会清空另外一个)
*/
@property (nullable, retain) NSInputStream *HTTPBodyStream;
2、使用HTTPBody可以直接获得请求体,而使用HTTPBodyStream流时不能直接获的请求体内容,获取方式如下:
    uint8_t sub[1024] = {0};
    NSInputStream *inputStream = request.HTTPBodyStream;
    NSMutableData *body = [[NSMutableData alloc] init];
    [inputStream open];
    while ([inputStream hasBytesAvailable]) {
        NSInteger len = [inputStream read:sub maxLength:1024];
        if (len > 0 && inputStream.streamError == nil) {
            [body appendBytes:(void *)sub length:len];
        }else{
            break;
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。