Developing iOS apps to invoke HTTP interfaces, get HTTP resources, have a fairly mature framework asihttprequest. I prefer to use the original API, which has many similarities with other object-oriented languages. This article describes the use of HTTP APIs in both synchronous and asynchronous requests. Directly on the code, the note is the document!
Synchronous Request : initiates an HTTP request, gets and processes the return value in the same thread
View Sourceprint?
01.
//创建URL对象
02.
NSString *urlStr = @
"http://blog.csdn.net/rongxinhua"
;
03.
NSURL *url = [[NSURL alloc] initWithString:urlStr];
04.
05.
//创建HTTP请求
06.
//方法1(注:NSURLRequest只支持Get请求,NSMutableURLRequest可支持Get和Post请求)
07.
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
08.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
09.
//方法2,使用工厂方法创建
10.
NSURLRequest *request = [NSURLRequest requestWithURL:url];
11.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
12.
//同时设置缓存策略和超时时间
13.
NSMutableURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:
15
];
14.
15.
//设置Http头
16.
NSDictionary *headers = [request allHTTPHeaderFields];
17.
[headers setValue:@
"iOS-Client-ABC"
forKey:@
"User-Agent"
];
18.
19.
//设置请求方法
20.
[request setHTTPMethod:@
"GET"
];
21.
[request setHTTPMethod:@
"POST"
];
22.
23.
//设置要发送的正文内容(适用于Post请求)
24.
NSString *content = @
"username=stanyung&pass<a href="
http:
//www.it165.net/edu/ebg/" target="_blank" class="keylink">word</a>=123";
25.
NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding];
26.
[request setHTTPBody:data];
27.
28.
//同步执行Http请求,获取返回数据
29.
NSURLResponse *response;
30.
NSError *error;
31.
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
32.
33.
//返数据转成字符串
34.
NSString *html = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
35.
36.
//(如果有错误)错误描述
37.
NSString *errorDesc = [error localizedDescription];
38.
39.
//获取状态码和HTTP响应头信息
40.
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
41.
NSInteger statusCode = [httpResponse statusCode];
42.
NSDictionary *responseHeaders = [httpResponse allHeaderFields];
43.
NSString *cookie = [responseHeaders valueForKey:@
"Set-Cookie"
];
Note: The above code, do not copy directly, just enumerate the HTTP common methods of invocation.
Asynchronous Request : initiates an HTTP request in one thread, returning the result to be processed in another thread. The asynchronous request does not need to wait for the result to be returned, and the current program can continue to execute as compared to the synchronization request. In Objective-c, asynchronous requests also have two implementations: one is to register a callback proxy and one is to use a callback code block.
A. How to register a callback agent:
View Sourceprint?
1.
[NSURLConnection connectionWithRequest:request delegate:self];
Need to implement the Nsurlconnectiondatadelegate protocol:
View Sourceprint?
1.
@interface
HttpDownloadService : NSObject<NSURLConnectionDataDelegate> {
2.
}
Implement the relevant protocol method:
View Sourceprint?
01.
NSMutableData *buff;
//暂存响应的数据
02.
bool finished =
false
;
//读完完整标记
03.
04.
//收到HTTP响应时调用
05.
-(
void
)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
06.
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
07.
NSDictionary *headers = [httpResponse allHeaderFields];
08.
buff = [[NSMutableData alloc] init];
09.
}
10.
11.
//读取返回数据时调用(可能会执行多次此方法)
12.
-(
void
)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
13.
[buff appendData:data];
14.
}
15.
16.
//读完数据完成时调用
17.
-(
void
)connectionDidFinishLoading:(NSURLConnection *)connection {
18.
NSString *html = [[NSString alloc] initWithData:buff encoding:NSUTF8StringEncoding];
19.
finished =
true
;
20.
}
Typically, data is transmitted over the network and is affected by factors such as bandwidth, and does not return all data at once, and you may be able to accept a complete HTTP response message several times. Therefore, (void) connection: (Nsurlconnection *) Didreceivedata: (NSData *) This method is likely to be executed several times.
In the example code, the Nsmutabledata is used to stage the received response data fragments, and each segment is then connected until the read is complete.
B. How to use the callback code block:
View Sourceprint?
1.
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:
2.
^(NSURLResponse *response, NSData *result, NSError *error){
//只会进入一次,方法内部已经实现了Buffer作用
3.
NSString *html = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
4.
}];
Unlike the Nsurlconnectiondatadelegate callback method, where the callback code block is called only once, it has already implemented the function of buffer inside, until the data is received intact before entering this block of code. Therefore, the result that you get in the code block can be used directly.
Note 1: The code example in this article will use the ARC encoding mode, so the newly created object does not explicitly call the release () method for recycling.
NOTE 2: If you test this example code new command line tool project, in the main function to execute the relevant code, the above two asynchronous execution situation, you most likely your program did not execute to the callback method or callback code block inside, because: in the main function, The main thread does not wait for blocking, all of a sudden, the callback code is in the child thread may not be executed or have not started execution, it has been due to the end of the main thread. To solve this problem, the code can be followed after the asynchronous method is called:
View Sourceprint?
1.
while
(!finished) {
2.
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
3.
}
The finished variable is exactly what is defined in the above two asynchronous HTTP examples to perform the completion.
Objective-c HTTP Common API synchronization requests and asynchronous requests