ios cfnetwork发送http请求简单实例
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();
}
void createThread(void)
{
pthread_t threadID;
pthread_create(&threadID, NULL,threadMain, NULL);
}
void getResponse(CFReadStreamRef readStream,CFStreamEventType event,void* infoPtr)
{
if(event==kCFStreamEventEndEncountered){
// CFHTTPMessageRef response=CFHTTPMessageCreateEmpty(kCFAllocatorDefault, NO);
CFHTTPMessageRef response=(CFHTTPMessageRef)infoPtr;
UInt32 statusCode=CFHTTPMessageGetResponseStatusCode(response);
CFDataRef responseData=CFHTTPMessageCopyBody(response);
UInt32 count=CFDataGetLength(responseData);
CFStringRef responseJson=CFStringCreateWithBytes(kCFAllocatorDefault, CFDataGetBytePtr(responseData), count, kCFStringEncodingUTF8, YES);
CFRelease(responseJson);
CFRelease(responseData);
cancelTheStream(readStream);
return;
}
if(event==kCFStreamEventHasBytesAvailable){
UInt8 buffer[100];
int length=CFReadStreamRead(readStream, buffer,100);
CFHTTPMessageAppendBytes((CFHTTPMessageRef)infoPtr, buffer, length);
return;
}
if(event==kCFStreamEventErrorOccurred){
//CFStreamError error=CFReadStreamGetError(readStream);
cancelTheStream(readStream);
return;
}
return;
}
@implementation AppDelegate
@synthesize window = _window;
@synthesize versionKey;
@synthesize messageQueueKey;
- (void)dealloc
{
[_window release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//create the url
CFStringRef urlString=CFSTR("your url");
 
相关新闻>>
- 发表评论
-
- 最新评论 更多>>