DetailsIPhoneMediumNetworkRequest is the content to be introduced in this article.NetworkProgramming-related content, describes in detail how to obtain or sendNetworkRequest. Let's just look at the details first.
1. Simple get requests
NetworkProgramming is something we often encounter. In the IPhone, the SDK provides good interfaces, including NSURL, NSMutableURLRequest, and NSURLConnection. Generally, we recommend that you use the Asynchronous Method of receiving data to request network connections. This type of network connection is divided into two steps. The first step is to create an NSURLConnection object and then directly call its start method to connect to the network. The second step is to use the delegate method to receive data. Here is a common method:
NetworkRequest section:
- NSString * urlString = [NSString stringWithFormat: @ "http://www.voland.com.cn: 8080/weather/weatherServlet? City = % @ ", kcityID];
- NSURL * url = [NSURL URLWithString: urlString];
- NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url];
- NSURLConnection * aUrlConnection = [[NSURLConnection alloc] initWithRequest: request delegate: self startImmediately: true];
- Self. urlConnection = aUrlConnection; // The urlConnection variable defined in the header file
- [Self. urlConnection start]; // starts to connect to the network.
- [AUrlConnection release];
- [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: YES];
The received data is mainly processed here.
- -(Void) connection :( NSURLConnection *) connection didReceiveResponse :( NSURLResponse *) response {
- NSLog (@ "response received: % @", response );
- }
- -(Void) connection :( NSURLConnection *) connection didReceiveData :( NSData *) data {
- NSLog (@ "received data :");
- }
- -(Void) connection :( NSURLConnection *) connection didFailWithError :( NSError *) error {
- NSLog (@ "data receiving error: % @", error );
- }
- -(Void) connectionDidFinishLoading :( NSURLConnection *) connection {
- NSLog (@ "connection completed: % @", connection );
- [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: NO];
- }
Ii. Post requests
For post requests, we mainly set the NSMutableURLRequest object. In get requests, we use the default object, and the actual content of these requests can be set. After setting, the other methods are the same as those in get mode:
- NSString *content=[[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
- [request setHTTPBody: content];
- [request setHTTPMethod: @"POST"];
- [request setValue:@"Close" forHTTPHeaderField:@"Connection"];
- [request setValue:@"www.voland.com.cn" forHTTPHeaderField:@"Host"];
- [request setValue:[NSString stirngWithFormat@"%d",[content length]] forHTTPHeaderField:@"Content-Length"];
Summary: DetailsIPhoneMediumNetworkThe request content has been introduced. I hope this article will help you!