iphone开发-http

如果只是简单的下载上传,我觉得这些就够了。

用到的类:NSURLRequest          NSURL            NSURLConnection

举简单的例子

【1】http  GET请求

参数url为目的请求URL地址:http://.......

注意url是经过URL编码之后的

- (NSString*) sendXMLRequest: (NSString*)url;
{
 [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    //NOTE with this way, cookie is send automatically, so it can be ignored

 //创建NSURLRequest
 NSString* urlEncoding = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
 NSURLRequest* urlrequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlEncoding] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:TIME_OUT];
 [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

  //通过NSURLConnection 发送NSURLRequest,这里是同步的,因此会又等待的过程,TIME_OUT为超时时间。

  //error可以获取失败的原因。
    NSError* error = nil;
    NSData* data = [NSURLConnection sendSynchronousRequest:urlrequest returningResponse:NULL error:&error];
    if(!error){
        NSString *stringData = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
        return stringData;
    }
    NSString* errorString = [NSString stringWithFormat:@"<error string=\"%@\"/>", [error localizedDescription]];
    return errorString;
}

【2】http POST请求

url是请求的目的URL地址,body是要发送的数据

- (NSString*) postURLRequest: (NSString*)url body:(NSString*)body
{
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString: url] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
   
    NSString *stringData = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
    return stringData;
}

 

 

转自:  http://yuxiang13115204.blog.163.com/blog/static/2680202220092148583437/

你可能感兴趣的:(iPhone开发)