如何从iOS应用程序执行URL请求?

时间:2012-06-10 12:42:24

标签: iphone objective-c cocoa-touch url

我想将以下请求发送到服务器。服务器已经知道如何处理它,但我该如何发送它?

http://www.********.com/ajax.php?script=logoutUser&username=****

2 个答案:

答案 0 :(得分:9)

对于同步请求,您将执行以下操作:

NSURL *url = [NSURL URLWithString:@"http://www.********.com/ajax.php?script=logoutUser&username=****"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

NSURLResponse *response;
NSError *error;
//send it synchronous
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// check for an error. If there is a network error, you should handle it here.
if(!error)
{
    //log response
    NSLog(@"Response from server = %@", responseString);
}

更新:对于执行异步请求,请参阅此example

答案 1 :(得分:0)

你可以这样做:

NSString *resp = [NSString stringWithContentsOfURL:url usedEncoding:enc error: &error];