我知道如何使用任何解释为here和here的HTTPClient发送post / get请求。但是现在我有一个连接到远程服务器的流套接字,我想使用这个套接字发送一个帖子请求。
我之前从未这样做过,坦率地说从未考虑过POST / GET通过套接字的概念。但我的谷歌搜索引导我到this,其中帖子是通过java套接字完成的。
我正在使用Apple提供的CFSocket库。无论如何,在Objective-C中使用套接字进行POST / GET吗?
答案 0 :(得分:7)
我已经能够使用普通的CFSocket进行GET / POST。
-(bool) sendHTTPHeader{
NSMutableString* requestString = [[NSMutableString alloc] init];
NSString *pathString = [NSString stringWithFormat:@"/remote_function.jsp?argument1=%@&argument2=%@",arg1,arg2 ];
[requestString appendFormat:@"GET %@ HTTP/1.x\r\n",pathString];
[requestString appendFormat:@"HOST:%@",your_host_here];
[requestString appendFormat:@"User-Agent:any\r\n"];
[requestString appendFormat:@"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n\r\n"];
/*If there are more parameters requested by server, put them here..*/
const char* sendString = [requestString UTF8String];
CFDataRef data = CFDataCreate(NULL, (const UInt8*)sendString, strlen(sendString));
CFSocketError err = CFSocketSendData(clientSocket, NULL, data, 0);
if (err != kCFSocketSuccess) {
NSLog(@"Error in sending data to the server");
CFRelease(data);
return FALSE;
}
[requestString release];
CFRelease(data);
return TRUE;
}
现在在你的套接字回调函数中你可以读取http响应。希望这对某人有帮助..
void socketCallback(CFSocketRef socket,CFSocketCallBackType type,CFDataRef address,const void *data,void *info){
if (type == kCFSocketDataCallBack) {
NSData *nsData = (NSData *)data;
if ([nsData length] == 0) {
NSLog(@"Connection dropped by remote socket");
return;
}
//Control reaches here when there is a chunk of data to read
CFDataRef df = (CFDataRef) data;
int len = CFDataGetLength(df);
CFRange range = CFRangeMake(0,len);
UInt8 buffer[len+1];
if(len <= 0) {
NSLog(@"No data read");
return;
}
memset((void*)buffer,0,sizeof(buffer));
CFDataGetBytes(df, range, buffer);
NSString *byteString = [[NSString alloc] initWithBytes:buffer length:len encoding:NSUTF8StringEncoding];
NSLog(@"byte string is : %@",byteString);
[byteString release];
}
}
答案 1 :(得分:3)