More practical, reproduced save
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
[OBJC]View Plaincopy
- Create a URL object
- NSString *urlstr = @ "Http://blog.csdn.net/rongxinhua";
- Nsurl *url = [[Nsurl alloc] initwithstring:urlstr];
- Create an HTTP request
- Method 1 (Note: Nsurlrequest only supports get requests, nsmutableurlrequest can support get and post requests)
- Nsurlrequest *request = [[Nsurlrequest alloc] Initwithurl:url];
- Nsmutableurlrequest *request = [[Nsmutableurlrequest alloc] Initwithurl:url];
- Method 2, use the factory method to create
- Nsurlrequest *request = [nsurlrequest requestwithurl:url];
- Nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:url];
- Set cache policy and timeout time
- Nsmutableurlrequest *request = [nsurlrequest requestwithurl:url cachepolicy: Nsurlrequestreloadignoringlocalcachedata timeoutinterval:15];
- Set HTTP Headers
- Nsdictionary *headers = [request Allhttpheaderfields];
- [Headers setValue:@ "IOS-CLIENT-ABC" Forkey:@ "User-agent"];
- Set Request method
- [Request Sethttpmethod:@ "GET"];
- [Request Sethttpmethod:@ "POST"];
- Set the body content to be sent (for post requests)
- NSString *content = @ "username=stanyung&password=123";
- NSData *data = [content datausingencoding:nsutf8StringEncoding];
- [Request Sethttpbody:data];
- Synchronously executes an HTTP request to get the returned data
- Nsurlresponse *response;
- Nserror *error;
- NSData *result = [nsurlconnection sendsynchronousrequest:request returningresponse:&response Error: &error];
- Return data into a string
- NSString *html = [[NSString alloc] initwithdata:result encoding:nsutf8StringEncoding];
- Error description (if there is an error)
- NSString *errordesc = [error localizeddescription];
- Get status code and HTTP response header information
- Nshttpurlresponse *httpresponse = (nshttpurlresponse *) response;
- Nsinteger StatusCode = [HttpResponse statusCode];
- Nsdictionary *responseheaders = [HttpResponse allheaderfields];
- 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:
[OBJC]View Plaincopy
- [Nsurlconnection connectionwithrequest:request delegate: Self];
Need to implement the Nsurlconnectiondatadelegate protocol:
[OBJC]View Plaincopy
- @interface httpdownloadservice:nsobject<nsurlconnectiondatadelegate> {
- }
Implement the relevant protocol method:
[OBJC]View Plaincopy
- Nsmutabledata *buff; //Staging response data
- BOOL finished = false; //Finish reading full Mark
- Called when an HTTP response is received
- -(void) connection: (nsurlconnection *) connection didreceiveresponse: (nsurlresponse *) Response {
- nshttpurlresponse *httpresponse = (nshttpurlresponse*) response;
- nsdictionary *headers = [HttpResponse allheaderfields];
- Buff = [[Nsmutabledata alloc] init];
- }
- Called when the return data is read (this method may be executed more than once)
- -(void) connection: (nsurlconnection *) connection didreceivedata: (nsdata *) data {
- [Buff appenddata:data];
- }
- Called when the data is finished reading
- -(void) connectiondidfinishloading: (nsurlconnection *) connection {
- nsstring *html = [[NSString alloc] initwithdata:buff encoding:nsutf8StringEncoding];
- Finished = true;
- }
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:
[OBJC]View Plaincopy
- [Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] Completionhandler:
- ^ (nsurlresponse *response, nsdata *result, nserror *error) { //will only enter once, the method has already implemented the buffer function inside
- nsstring *html = [[NSString alloc] initwithdata:result encoding:nsutf8StringEncoding];
- }];
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:
[OBJC]View Plaincopy
- while (!finished) {
- [[Nsrunloop Currentrunloop] runmode:nsdefaultrunloopmode beforedate:[nsdate Distantfuture]];
- }
The finished variable is exactly what is defined in the above two asynchronous HTTP examples to perform the completion.
@ Capacity Xinhua Technology Blog-Http://blog.csdn.net/rongxinhua-original articles, reproduced please specify the source
"OBJECTIVE-C" HTTP common API, synchronous request and asynchronous request [go]