Source: http://www.cnblogs.com/edisonfeng/p/3830224.html
First, the service side
1, the main structure:
2, the main code:
1) Web. xml
<?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "2.5" xmlns= "http://java.sun.com/xml/ns/ Java ee " xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance " xsi:schemalocation=" http://java.sun.com/ Xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> < servlet-name>loginservlet</servlet-name><!--lsdkalskdfjasdkfj--> <servlet-class> com.wiscom.servlet.loginservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/loginservlet</url-pattern > </servlet-mapping></web-app>
2) Loginservlet.java
Package Com.wiscom.servlet;import Java.io.ioexception;import Java.io.printwriter;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class LoginServlet Extends HttpServlet {public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexceptio N, IOException {//TODO auto-generated Method Stub response.setcontenttype ("Text/html;charset=utf-8"); Request.setcharacterencoding ("Utf-8");//Set the parameter decoding type, must be consistent with the page String sname=request.getparameter ("name"); String spassword=request.getparameter ("PSW"); PrintWriter out = Response.getwriter (); if (sname.equals ("admin") &&spassword.equals ("admin")) {Out.print ("sname+"), you have successfully logged in!! "); }else{Out.print (sname+ ", User name password is wrong!! "); }} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { This.doget (request, response); }}
Second, the client
1. header file: NetCenter.h
#import <Foundation/Foundation.h> @interface netcenter:nsobject@property (nonatomic,retain) Nsmutabledata * Receivedata; @property (nonatomic,assign) int datapackserialno;-(void) httpgetsyn;-(void) httppostsyn;-(void) httpgetnosyn;-(void) Httppostnosyn; @end
2. Implementation file: NETCENTER.M
#import "NetCenter.h" @implementation netcenter@synthesize receivedata=_receivedata @synthesize datapackserialno=_ datapackserialno;-(void) httpgetsyn{NSLog (@ "Httpgetsyn ..."); /* NSString *urlstring =url; Nsmutableurlrequest *request = [[Nsmutableurlrequest alloc] init]; [Request Seturl:[nsurl urlwithstring:urlstring]; [Request sethttpmethod:@ "GET"]; nshttpurlresponse* urlresponse = nil; Nserror *error = [[Nserror alloc] init]; NSData *responsedata = [nsurlconnection sendsynchronousrequest:request returningresponse:&urlresponse Error: &error]; nsmutablestring *result = [[Nsmutablestring alloc] Initwithdata:responsedata encoding:nsutf8stringencoding]; NSLog (@ "The result string is:%@", result); *///First step, create URL nsurl *url = [Nsurl urlwithstring:@ "http://10.0.0.96:8080/app_server/LoginServlet?name=admin&psw= Admin "]; The second step is to create a network request via the URL nsurlrequest *request = [[Nsurlrequest alloc]initwithurl:url Cachepolicy:nsurlrequestuseprotOcolcachepolicy Timeoutinterval:10]; Nsurlrequest initialization Method first parameter: Request access path, second parameter: Cache protocol, third parameter: Network request time-out (seconds)/* Where cache protocol is an enumeration type contains: Nsurlrequestuseprotocolcachepolic Y (Base policy) Nsurlrequestreloadignoringlocalcachedata (ignoring local cache) Nsurlrequestreturncachedataelseload (first using the cache, if there is no local cache, Downloaded from the original address) Nsurlrequestreturncachedatadontload (use local cache, never download, if there is no cache locally, the request fails, this policy is used for offline operation) Nsurlrequestreloadignoringlocalandremotecachedata (ignoring any caching policies, whether local or remote, always re-downloaded from the original address) Nsurlrequestreloadrevalidatingcachedata (if the local cache is valid, do not download, and any other case is re-downloaded from the original address) *///Third step, connect server NSData *received = [NSURLC Onnection sendsynchronousrequest:request Returningresponse:nil Error:nil]; NSString *str = [[NSString alloc]initwithdata:received encoding:nsutf8stringencoding]; NSLog (@ "%@", str);} -(void) httppostsyn{NSLog (@ "Httppostsyn ..."); The first step is to create the URL nsurl *url = [Nsurl urlwithstring:@ "Http://10.0.0.96:8080/app_server/LoginServlet"]; Second step, create request NSString *poststr = [[NSString alloc] initwithformat:@ "NAme=%@&psw=%@ ", @" admin ", @" admin "]; NSData *postdata = [Poststr datausingencoding:nsutf8stringencoding]; Nsmutableurlrequest *request = [[Nsmutableurlrequest alloc]initwithurl:url CachePolicy: Nsurlrequestuseprotocolcachepolicy Timeoutinterval:10]; [Request sethttpmethod:@ "POST"];//Setup requested by post, default to get [request sethttpbody:postdata];//Set parameters//third step, connect server NSData *received = [nsurlconnection sendsynchronousrequest:request returningresponse:nil Error:nil]; NSString *backstr = [[NSString alloc]initwithdata:received encoding:nsutf8stringencoding]; NSLog (@ "%@", Backstr);} -(void) httpgetnosyn{NSLog (@ "Httpgetnosyn ..."); The first step is to create the URL nsurl *url = [Nsurl urlwithstring:@ "http://10.0.0.96:8080/app_server/LoginServlet?name=admin&psw= Admin "]; The second step, create the request nsurlrequest *request = [[Nsurlrequest alloc]initwithurl:url CachePolicy: Nsurlrequestuseprotocolcachepolicy Timeoutinterval:10]; Step three, connect the server nsurlconnection *connection = [[NsurlconnectiOn Alloc]initwithrequest:request delegate:self]; }-(void) httppostnosyn{NSLog (@ "Httppostnosyn ..."); The first step is to create the URL nsurl *url = [Nsurl urlwithstring:@ "Http://10.0.0.96:8080/app_server/LoginServlet"]; The second step, create the request nsstring *poststr = [[NSString alloc] initwithformat:@ "name=%@&psw=%@", @ "admin", @ "admin"]; NSData *postdata = [Poststr datausingencoding:nsutf8stringencoding]; Nsmutableurlrequest *request = [[Nsmutableurlrequest alloc]initwithurl:url CachePolicy: Nsurlrequestuseprotocolcachepolicy Timeoutinterval:10]; [Request sethttpmethod:@ "POST"]; [Request Sethttpbody:postdata]; Step three, connect the server nsurlconnection *connection = [[Nsurlconnection alloc]initwithrequest:request delegate:self];} /*************5, asynchronous request Proxy method [start]****************///Call this method when receiving a server response-(void) connection: (Nsurlconnection *) Connection didreceiveresponse: (Nsurlresponse *) response{nshttpurlresponse *res = (Nshttpurlresponse *) response; NSLog (@ "%@", [res allheaderfields]); SeLf.receivedata = [Nsmutabledata data];//The initialization self.datapackserialno=0 of the data storage object; NSLog (@ "Received server response ... ");} Called when the server transmits data, this method executes several times according to the data size-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{ NSLog (@ "received the packet sent back by the server, packet number:%d", self.datapackserialno); [Self.receivedata Appenddata:data]; Self.datapackserialno+=1;} This method is called after the data is passed-(void) connectiondidfinishloading: (nsurlconnection *) connection{NSLog (@ "Data transfer complete, output all results ... "); NSString *receivestr = [[NSString alloc]initwithdata:self.receivedata encoding:nsutf8stringencoding]; NSLog (@ "%@", Receivestr);} During a network request, any errors (network disconnection, connection timeouts, etc.) are entered into this method-(void) connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error {NSLog (@ "Network request error:%@", [Error localizeddescription]);} Proxy method for/*************5, asynchronous request [end]****************/@end
3. Call
-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchOptions { Self.window = [[UIWindow alloc] initwithframe:[[uiscreen mainscreen] bounds]]; Netcenter *netcenter=[[netcenter Alloc]init]; /***************** Sync request ****************/ //[netcenter Httpgetsyn]; [Netcenter Httppostsyn]; /***************** Asynchronous Request ****************/ //[netcenter Httpgetnosyn]; [Netcenter Httppostnosyn]; Self.window.backgroundColor = [Uicolor whitecolor]; [Self.window makekeyandvisible]; return YES;}
Third, testing
1. Synchronous get
2. Synchronous Post
3. Asynchronous get
4. Asynchronous post
Third, expansion
1. HTTP and HTTPS
Http://www.cnblogs.com/stan0714/archive/2012/03/21/2409872.html
2. iOS network programming theory and examples
http://blog.csdn.net/hgy2011/article/details/8676084
Http:get,post in iOS, synchronous, asynchronous