【发布时间】:2009-02-26 10:05:18
【问题描述】:
我想使用 HTTP 连接到服务器,向它发送一个字符串并从服务器接收响应字符串。关于如何通过 url 连接到服务器、发送和接收消息的任何想法?
【问题讨论】:
标签: iphone httpwebrequest communication
我想使用 HTTP 连接到服务器,向它发送一个字符串并从服务器接收响应字符串。关于如何通过 url 连接到服务器、发送和接收消息的任何想法?
【问题讨论】:
标签: iphone httpwebrequest communication
// 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
}
【讨论】:
我建议使用来自 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 数据和文件变得容易。
【讨论】:
您可以使用NSMutableURLRequest 和NSURLConnection 类连接到服务器、发送字符串并接收响应。一个好的起点是Introduction to the URL Loading System。
【讨论】: