[IOS Multithreading & Networking-2.0]-Sending receiving server information

Source: Internet
Author: User

A. Building A Java ServerBuild a simple server with Eclipse, Tomcat, and STRUTS2 frameworks 1. Prepare the appropriate version of the JDK, Eclipse EE, Tomcat, struts2 Framework Package 2. Configure the JDK and Tomcat system variables 3. Create a dynamic Web Project in Eclipse, Tick create WEB.XML4. Unzip the app example in a struts2, and refer to the Web. XML and Struts.xml configuration in it 5. Configure Tomcat, note the path and the publishing path for the correct server, and do not use the default Eclipse path 6. Introduce a resource file to create the appropriate AC Tionsupport can handle external information. basic server requests in B.ios 1.get and PostGet and Post are the two most common HTTP methods for interacting with the server
GET
The semantics of Get is the resource that gets the specified URL
Add the data in the form of Variable=value, followed by the URL to which the action points, and both use "?" Connection, using "&" connection between variables
Seemingly unsafe, because in the transfer process, the data is placed in the requested URL, the amount of data transferred is small, mainly because the URL length is limited by POST
The semantics of post is to add data to the resource of the specified URL
Place the data in the data body and pass it to the URL that the action points to, in the same way that the variable and the value correspond
All data is not visible to users
Can transfer a lot of data, upload files can only use post C.ios Sending network requests1. Send Step instantiation URL (network resource) establish urlrequest based on URL (network request)
Default is GET request
For a POST request, the requested data body needs to be created
Send network requests with URLConnection (establish connection)
Get results

Nsurlconnection provides two static methods to send network requests directly to the server in a synchronous or asynchronous manner
Sync Request:
SendSynchronousRequest:returningResponse:error:
Asynchronous Request:
SendAsynchronousRequest:queue:completionHandler: 2. Binary stream in network transmissionIn the process of network request, the process of receiving data is actually implemented by Nsurlconnectiondatadelegate, and the common proxy methods include:

The server begins to return data, ready to work
(void) Connection:didreceiveresponse:
When the data returned by the server is received, this method is called multiple times
-(void) Connection:didreceivedata:
Data received, the final processing of data
(void) Connectiondidfinishloading:
Network connection Error
-(void) Connection:didfailwitherror: D. Practice Code  1. Using GET Requests
1(1). Send a GET request using a synchronous method (not commonly used)2 /** Send a GET message*/3- (void) Testget {4NSString *requeststr = [NSString stringWithFormat:@"http://192.168.0.21:8080/mytestserver/login?user=%@&password=%@", Self.userField.text, Self.passwordField.text];5    6Nsurl *url =[Nsurl Urlwithstring:requeststr];7    8     //The default is a GET request9Nsurlrequest *request =[Nsurlrequest Requestwithurl:url];Ten     One     //sending requests using the synchronous method A [self sendsynrequest:request]; - } -  the /** Synchronous Send request*/ -- (void) Sendsynrequest: (Nsurlrequest *) Request { -     //Send messages synchronously -NSData *data =[nsurlconnection sendsynchronousrequest:request returningresponse:nil Error:nil]; +     - [self dealwithresponsedata:data]; + } A  at /** Processing return Data*/ -- (void) Dealwithresponsedata: (NSData *) Data { -     //parsing Data -     if(data) {//Get Return Data -         //Unblock screen lock - [Mbprogresshud Hidehud]; in         -         //parsing JSON data toNsdictionary *dict =[nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutableleaves Error:nil]; +         -         //processing the returned data theNSString *result = dict[@"Success"]; *         if(Result) { $ [Mbprogresshud Showsuccess:result];Panax Notoginseng}Else { -result = dict[@"Error"]; the             if(Result) { + [Mbprogresshud Showerror:result]; A             } the         } +}Else { -[Mbprogresshud ShowError:@"the Internet is busy, please try again later"]; $     } $}
(2). Send a GET request using an asynchronous method
 1  /*   */ 2 -(void ) Sendasynrequest: (nsurlrequest *) request { 3  nsoperationqueue *queue = [Nsoperationqueue Mainqueue];  4  [nsurlconnection sendasynchronousrequest:request Queue:queue completionhandler:^ (Nsurlresponse *response, NSData *data, nserror *connectionerror) {  5  6   [self dealwithresponsedata:data];  7   8 } 
2. Sending an asynchronous request using the Nsurlconnectiondatadelegate Proxy (1) Compliance Protocol
1 @interface Viewcontroller () <NSURLConnectionDataDelegate>
(2) Set up agent, send request
1 /*  */2 -(void) Sendasynrequestwithdelegate: (Nsurlrequest *) Request {  3     delegate: self]; 4     [connection start]; 5 }
(3) Implement Proxy method
1 #pragmaMark-nsurlconnectiondatadelegate Proxy method2 /** Received server response*/3- (void) Connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) Response {4NSLog (@"Didreceiveresponse");5Self.data =[Nsmutabledata data];6 }7 8 /** received data, will be called multiple times, the data is split to receive*/9- (void) Connection: (Nsurlconnection *) connection didreceivedata: (NSData *) Data {TenNSLog (@"Didreceivedata"); One [Self.data Appenddata:data]; A } -  - /** Receive data complete*/ the- (void) Connectiondidfinishloading: (Nsurlconnection *) Connection { -NSLog (@"connectiondidfinishloading"); - [self dealWithResponseData:self.data]; -}
3. Using the POST request
1 #pragmaMark-post2- (void) Testpost {3NSString *requeststr = [NSString stringWithFormat:@"Http://192.168.0.21:8080/MyTestServer/login"];4Nsurl *url =[Nsurl Urlwithstring:requeststr];5    6Nsmutableurlrequest *request =[Nsmutableurlrequest Requestwithurl:url];7Request.timeoutinterval =5;8    9     //Set as POST requestTenRequest. HttpMethod =@"POST"; One     A     //set the request header -[Request SetValue:@"iOS"Forhttpheaderfield:@"user-agent"]; -     the     //set the request body -NSString *param = [NSString stringWithFormat:@"user=%@&password=%@", Self.userField.text, Self.passwordField.text]; -Request. Httpbody =[param datausingencoding:nsutf8stringencoding]; -     +     //Send Request -     //using the main thread to handle UI refreshes +Nsoperationqueue *queue =[Nsoperationqueue Mainqueue]; A[Nsurlconnection sendasynchronousrequest:request queue:queue completionhandler:^ (NSURLResponse *response, NSData * Data, Nserror *connectionerror) { at [self dealwithresponsedata:data]; -     }]; -    -}
4. Set request properties (1) Set timeout period
1     // using variable request 2     Nsmutableurlrequest *request = [Nsmutableurlrequest requestwithurl:url]; 3     // set the request time-out period 4     5;
4. Chinese transcoding using UTF8 transcoding [Urlstr stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];
1     NSString *requeststr = [NSString stringWithFormat:@ "http://192.168.0.21:8080/MyTestServer/login?user= %@&password=%@", Self.userField.text, Self.passwordField.text]; 2    3     // transcoding is required because the URL cannot be delivered in Chinese 4     REQUESTSTR = [Requeststr stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];

[IOS Multithreading & Networking-2.0]-Sending receiving server information

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.