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