//创建Url
NSURL *url = [NSURL URLWithString:@"你的url地址"];
//创建请求
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
[request setHTTPMethod:@"POST"];
NSString *str = @"用户名参数=用户名&密码参数=密码";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
//连接服务器,现在使用的是异步请求,回调需要在NSURLConnectionDelegate中写
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
下面是异步请求的代理方法:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
NSLog(@"%@",[res allHeaderFields]);
self.receiveData = [NSMutableData data];
}
//接收到服务器传输数据的时候调用,此方法根据数据大小执行若干次
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.receiveData appendData:data];
}
//数据传完之后调用此方法
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *receiveStr = [[NSString alloc]initWithData:self.receiveData encoding:NSUTF8StringEncoding];
NSLog(@"%@",receiveStr);
}
//网络请求过程中,出现任何错误(断网,连接超时等)会进入此方法
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"%@",[error localizedDescription]);
}