#pragma mark--
#pragma mark 按键响应函数
//1.用get方法上传参数、获取数据
- (IBAction)getMsgWithGet:(id)sender {
NSString *baseUrl=@"http://getMsgWithGet.php";
NSString *withString=@"name=xxx&msg=我要发送的信息";
NSString *urlString=[NSString stringWithFormat:@"%@?%@",baseUrl,withString];
NSURL *url=[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
}
//2.用post方法上传参数、获得数据
- (IBAction)getMsgWithPost:(id)sender {
NSString *baseUrl=@"http://getMsgWithPost.php";
NSString *withString=@"name=zzz&msg=我要通过Post发送的信息";
NSURL *url=[NSURL URLWithString:[baseUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"post"];
NSData *parmData=[withString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:parmData];
//可以通过这种方式在httpheadfiled中添加额外的信息
[request addValue:[NSString stringWithFormat:@"%d",parmData.length] forHTTPHeaderField:@"Content-Length"];
[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[NSURLConnection connectionWithRequest:request delegate:self];
}
#pragma mark--
#pragma mark NSURLConnection协议方法
//连接成功后调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)respons{
netData.length=0;
NSHTTPURLResponse *res=(NSHTTPURLResponse *)respons;
NSLog(@"%@",res.allHeaderFields);
}
//接收数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[netData appendData:data];
}
//数据接收完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *resultString=[[NSString alloc]initWithData:netData encoding:NSUTF8StringEncoding];
self.myLabel.text=resultString;
}
pragma mark--
#pragma mark 3.ASI协议方法示例
//导入头文件
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
-(void *)ASIgetDataWithID:(id)alumbID andWithModelIndex:(int)modelIndex
{
NSString *baseUrl = [NSString stringWithFormat:@"https://api.douban.com/v2/online/%@/photos",alumbID];
NSURL *url = [NSURL URLWithString:baseUrl];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
__weak ASIHTTPRequest *wRequest = request;
// [wRequest setCompletionBlock:^{//这样子士不行的
[request setCompletionBlock:^{
NSDictionary *phtotDict = [NSJSONSerialization JSONObjectWithData:wRequest.responseData options:NSJSONReadingMutableContainers error:nil];
pArr = [NSMutableArray array];
//封装数据为model
NSMutableArray *mtuPhtotArr = phtotDict[@"photos"];
for(int j = 0;j < mtuPhtotArr.count; j++)
{
NSDictionary *phtot = [NSDictionary dictionary];
phtot = mtuPhtotArr[j];
NSString *phtotUrl = phtot[@"image"];
[pArr addObject:phtotUrl];
}
LYGDataModel *model = myMutArr[modelIndex];
model.cellImageArr = pArr;
[myTableView reloadData];
}];
[request setFailedBlock:^{
NSLog(@"%@",request.error);
}];
[request startAsynchronous];
}