CFNetwrok网络请求4

//
//  CFNetworkTest4.m
//  TestCF
//
//  Created by Jabez on 15/5/11.
//  Copyright (c) 2015年 John. All rights reserved.
//

#import "CFNetworkTest4.h"
#import <pthread.h>

@implementation CFNetworkTest4

static CFRunLoopRef backgroundRunLoop;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void releaseContext(void *infoPtr) {
    CFRelease(infoPtr);
}

void *retainContext(void *infoPtr) {
    CFRetain(infoPtr);
    return infoPtr;
}

void cancelTheStream(CFReadStreamRef readStream) {
    CFReadStreamUnscheduleFromRunLoop(readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
    CFReadStreamClose(readStream);
    CFRelease(readStream);
}

void *threadMain(void *info) {
    pthread_mutex_lock(&mutex);
    backgroundRunLoop = CFRunLoopGetCurrent();
    CFRunLoopSourceContext context = {0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
    CFRunLoopSourceRef source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&mutex);
    CFRunLoopRun();
    
    return NULL;
}

void createThread(void) {
    pthread_t threadID;
    pthread_create(&threadID, NULL, threadMain, NULL);
}

void getResponse(CFReadStreamRef readStream, CFStreamEventType type, void *infoPtr) {
    if (type == kCFStreamEventEndEncountered) {
        CFHTTPMessageRef response = (CFHTTPMessageRef)infoPtr;
        
        CFIndex statusCode = CFHTTPMessageGetResponseStatusCode(response);
        CFDataRef responseData = CFHTTPMessageCopyBody(response);
        
        CFIndex count = CFDataGetLength(responseData);
        CFStringRef responseJson = CFStringCreateWithBytes(kCFAllocatorDefault, CFDataGetBytePtr(responseData), count, kCFStringEncodingUTF8, YES);
        NSString *jsonString = [NSString stringWithFormat:@"%@", (__bridge NSString *)responseJson];
        NSLog(@"jsongString: %@", jsonString);
        
        CFRelease(responseJson);
        CFRelease(responseData);
        cancelTheStream(readStream);
    } else if (type == kCFStreamEventHasBytesAvailable) {
        UInt8 buffer[100];
        CFIndex length = CFReadStreamRead(readStream, buffer, 100);
        CFHTTPMessageAppendBytes((CFHTTPMessageRef)infoPtr, buffer, length);
    } else if (type == kCFStreamEventErrorOccurred) {
        cancelTheStream(readStream);
        return;
    }
}

- (void)sendMessage
{
    [self request];
}

- (void)request
{
    CFStringRef urlString = CFSTR("http://jabez.local/~jabez/test/response/response0");
    CFURLRef url = CFURLCreateWithString(kCFAllocatorDefault, urlString, NULL);
    
    CFStringRef method = CFSTR("POST");
    
    CFHTTPMessageRef request = CFHTTPMessageCreateRequest(kCFAllocatorDefault, method, url, kCFHTTPVersion1_1);
    
    CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Content-Type"), CFSTR("application-json"));
    
    CFStringRef jsonBody = CFSTR("key=Test4");
    CFDataRef jsonData = CFStringCreateExternalRepresentation(kCFAllocatorDefault, jsonBody, kCFStringEncodingUTF8, 0);
    CFHTTPMessageSetBody(request, jsonData);
    
    CFHTTPMessageRef response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, NO);
    CFStreamClientContext context = {0, response, retainContext, releaseContext, NULL};
    
    CFOptionFlags registeredEvent = kCFStreamEventHasBytesAvailable | kCFStreamEventEndEncountered | kCFStreamEventErrorOccurred;
    CFReadStreamRef readStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, request);
    CFReadStreamSetClient(readStream, registeredEvent, getResponse, &context);

    if (backgroundRunLoop == NULL) {
        createThread();
        pthread_cond_wait(&cond, &mutex);
    }
    
    CFReadStreamScheduleWithRunLoop(readStream, backgroundRunLoop, kCFRunLoopCommonModes);
    CFReadStreamOpen(readStream);
    
    CFRelease(url);
    CFRelease(urlString);
    CFRelease(method);
    CFRelease(request);
    CFRelease(jsonBody);
    CFRelease(jsonData);
}

@end

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。