1.同步方式请求——Get方式
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.bafdaidu.com"]];
req.timeoutInterval = 15;
[req setHTTPMethod:@"GET"];
// Response对象,用来得到返回后的数据,比如,用statusCode==200 来判断返回正常
NSHTTPURLResponse *response;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
// 处理返回的数据
NSString *strReturn = [[NSString alloc] initWithData:returnDataencoding:NSUTF8StringEncoding];
NSLog(@"%@",strReturn);
NSLog(@"%d",[response statusCode]);
// 对象还是要释放的
[strReturn release];
2.异步方式请求
@interface MoreViewController : UIViewController<</span>NSURLConnectionDelegate>
urlString = [urlString stringByAddingPercentEsc
[request setURL:[NSURL URLWithString: urlString]];
[request setCachePolicy:NSURLRequestReloadIgnori
[request setTimeoutInterval: 60];
[request setHTTPShouldHandleCooki
[request setHTTPMethod:@"GET"];
#pragma mark- NSURLConnectionDelegate 协议方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse{
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError*)error{
}
- (void)connectionDidFinishLoadi
}
3.POST方式:
注意这个类要
UIResponder <UIApplicationDelegate, NSURLConnectionDelegate>
在请求的地方加上一下的代码:
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.bafdaidu.com"]];
req.timeoutInterval = 15;
[req setHTTPMethod:@"POST"];
NSData *postdata;
postdata = [@"{}" dataUsingEncoding:NSASCIIStringEncoding];
if(postdata!=nil){
[req setHTTPBody:postdata];
[req setValue:[NSString stringWithFormat:@"%d", [postdata length]] forHTTPHeaderField:@"Content-Length"];
[req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
}
[[NSURLConnection connectionWithRequest:req delegate:self] start];
#pragma mark NSURLConnectionDelegate
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
int statusCode = [((NSHTTPURLResponse*)response) statusCode];
NSLog(@"%@: %@ : statusCode=%d", NSStringFromSelector(_cmd), self, statusCode );
if( statusCode >= 400 )
{
}
data = [[NSMutableData alloc] init];
long long totalBytes = [response expectedContentLength];
NSLog(@"总共的字数为:%lld",totalBytes);
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)receiveData
{
[data appendData:receiveData];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString * strValue = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", strValue);
NSLog(@"recieve finish");
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"%@: %@", NSStringFromSelector(_cmd), self );
[connection cancel];
int errorCode = [error code];
NSString *errorMessage = [NSString stringWithFormat:@"ErrorCode : %d", errorCode];
}
//end