[ios]get,post请求 【转】
//========get同步===========//
NSURL * getSynurl=[NSURL URLWithString:@""];
NSURLRequest * getSynrequest=[[NSURLRequest alloc] initWithURL:getSynurl cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:10];
// NSURLRequestUseProtocolCachePolicy(基础策略)
//
// NSURLRequestReloadIgnoringLocalCacheData(忽略本地缓存)
//
// NSURLRequestReturnCacheDataElseLoad(首先使用缓存,如果没有本地缓存,才从原地址下载)
//
// NSURLRequestReturnCacheDataDontLoad(使用本地缓存,从不下载,如果本地没有缓存,则请求失败,此策略多用于离线操作)
//
// NSURLRequestReloadIgnoringLocalAndRemoteCacheData(无视任何缓存策略,无论是本地的还是远程的,总是从原地址重新下载)
//
// NSURLRequestReloadRevalidatingCacheData(如果本地缓存是有效的则不下载,其他任何情况都从原地址重新下载)
NSError *err;
NSData *getSynrecived=[NSURLConnection sendSynchronousRequest:getSynrequest returningResponse:nil error:&err];
NSString * getSynstr=[[NSString alloc] initWithData:getSynrecived encoding:(NSUTF8StringEncoding)];
NSLog(@"get同步请求得到的数据是:%@",getSynstr);
//=======post同步============//
NSURL * postSynurl=[NSURL URLWithString:@""];
NSMutableURLRequest * postSynrequest=[[NSMutableURLRequest alloc] initWithURL:postSynurl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
[postSynrequest setHTTPMethod:@"POST"];
NSString *str=@"参数";
NSData * data=[str dataUsingEncoding:NSUTF8StringEncoding];
[postSynrequest setHTTPBody:data];
//- (void)setAllHTTPHeaderFields:(NSDictionary *)headerFields 设置头报文信息
//- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
NSData * postsynreceived=[NSURLConnection sendSynchronousRequest:postSynrequest returningResponse:nil error:nil];
NSString *postSynstr=[[NSString alloc] initWithData:postsynreceived encoding:NSUTF8StringEncoding];
//=========get异步========//
NSURL * geturl=[NSURL URLWithString:@""];
NSURLRequest *getrequest = [[NSURLRequest alloc]initWithURL:geturl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:getrequest delegate:self];
//=========post异步=======//
NSURL * posturl=[NSURL URLWithString:@""];
NSMutableURLRequest *postrequest = [[NSMutableURLRequest alloc]initWithURL:posturl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
[postrequest setHTTPMethod:@"POST"];
NSString *poststr = @"参数";
NSData *postdata = [poststr dataUsingEncoding:NSUTF8StringEncoding];
[postrequest setHTTPBody:postdata];
NSURLConnection *postconnection = [[NSURLConnection alloc]initWithRequest:postrequest delegate:self];
//[postconnection start];
//以下是异步请求的代理方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
//服务器收到请求后回应
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//接收数据,此方法不仅被调用一次
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
}
-(void)connection:(NSURLConnection *)connection{
}