如何在iPhone上使用HTTP通信?
答
// create the request
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData that will hold
// the received data
// receivedData is declared as a method instance elsewhere
receivedData=[[NSMutableData data] retain];
} else {
// inform the user that the download could not be made
}
答
您可以连接到服务器,发送字符串,并使用NSMutableURLRequest
和NSURLConnection
类接收响应。一个好的开始是Introduction to the URL Loading System。
答
我建议使用All-Seeing Interactive的优秀ASIHTTPRequest源代码:http://allseeing-i.com/ASIHTTPRequest。我正在这样做,所以有几个已发布的iPhone应用程序,所以你可以确信代码非常稳定。
这是一个围绕CFNetwork API的包装,它使与Web服务器通信更加单调乏味。它用Objective-C编写,适用于Mac OS X和iPhone应用程序。
它适用于执行基本HTTP请求并与基于REST的服务(GET/POST/PUT/DELETE)交互。 ASIFormDataRequest子类可以使用multipart/form-data轻松提交POST数据和文件。
当我学习时,很高兴知道如何使用特定代码完成工作。之后,我可能希望使用开源代码简化工作。不管怎么说,还是要谢谢你。 – 2009-02-27 08:03:16