OBJECT-CHTTP请求

来源:互联网 发布:淘宝0元换购啥意思 编辑:程序博客网 时间:2024/06/05 19:46

异步发送HTTP请求的代码

原:http://www.cocoachina.com/newbie/tutorial/2010/0318/727.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
NSMutableData* buf = [[NSMutableDataalloc] initWithLength:0];
NSURLConnection* connection = [[NSURLConnectionalloc] initWithRequest:req delegate:self];
 
// 收到响应时, 会触发
- (void)connection:(NSURLConnection*)aConnection didReceiveResponse:(NSURLResponse*)aResponse;
// 你可以在里面判断返回结果, 或者处理返回的http头中的信息
 
// 每收到一次数据, 会调用一次
- (void)connection:(NSURLConnection*)aConn didReceiveData:(NSData*)data;
// 因此一般来说,是
- (void)connection:(NSURLConnection*)aConn didReceiveData:(NSData*)data
{
    [buf appendData:data];
}
// 当然buffer就是前面initWithRequest时同时声明的.
 
// 网络错误时触发
- (void)connection:(NSURLConnection*)aConn didFailWithError:(NSError*)error;
 
// 全部数据接收完毕时触发
- (void)connectionDidFinishLoading:(NSURLConnection*)aConn;

同步发送HTTP请求的代码


1
2
3
4
5
6
7
8
9
10
11
// 初始化請求
        NSMutableURLRequest*request = [[NSMutableURLRequestalloc] init];        
// 設置URL
        [request setURL:[NSURLURLWithString:urlStr]];
// 設置HTTP方法
        [request setHTTPMethod:@"GET"];
// 發送同步請求, 這裡得returnData就是返回得數據楽
        NSData*returnData = [NSURLConnectionsendSynchronousRequest:requestreturningResponse:nilerror:nil];
// 釋放對象
        [request release];