是的,您可以使用 NSOutputStream 发送 HTTP GET/POST 请求。
1.make & 打开你的流。
2.当流准备好写入时,NSStreamEventHasSpaceAvailable
事件将在方法中发送:
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
https://developer.apple.com/documentation/foundation/nsstreamdelegate/1410079-stream?language=objc
3.制作一个CFHTTPMessageRef
&并写入数据。
像这样的代码:
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{
switch (eventCode) {
case NSStreamEventOpenCompleted:{
//
}
break;
case NSStreamEventHasSpaceAvailable:{
[self sendHTTPMessage];
}
break;
default:{
//
}
break;
}
- (void)sendHTTPMessage{
//create a http GET message
CFStringRef requestMethod = (CFStringRef)CFAutorelease(CFSTR("GET"));
CFHTTPMessageRef httpRequest = (CFHTTPMessageRef)CFAutorelease(CFHTTPMessageCreateRequest(kCFAllocatorDefault, requestMethod, (__bridge CFURLRef)yourURL,kCFHTTPVersion1_1));
//set HTTP header
CFHTTPMessageSetHeaderFieldValue(httpRequest, (__bridge CFStringRef)@"Host", (__bridge CFStringRef)@"yourhost.com");
CFHTTPMessageSetHeaderFieldValue(httpRequest, (__bridge CFStringRef)@"Connection", (__bridge CFStringRef)@"close");
//set HTTP Body
...
//let's send it
CFDataRef serializedRequest = CFHTTPMessageCopySerializedMessage(httpRequest);
NSData *requestData = (__bridge_transfer NSData *)serializedRequest;
[self.outStream write:requestData.bytes maxLength:requestData.length];
[self.outStream close];
}
请记住,关键是将 CFHTTPMessageRef 转换为要写入的字节。