Mobile clients often need to communicate with the backend server, upload or download data, the most frequently used way is HTTP Get, now we learn to use the Get method in iOS projects to communicate with the server.
"One" server-side implementation
(1) First install the eclipse or myeclipse that can be developed for Java EE, and configure the Tomcat environment.
I'm using Eclipse Mars here. The Tomcat version number is 8. Then create a new dynamic Web Project. The name is myserver.
Then create a new JSP File in the webcontent. The name is index. The current folder structure such as the following:
。
(2) Then the following is implemented in HELLO.JSP: For client requests, I will return "Hello name". Otherwise, no paras is returned.
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><%string name = Request.getparameter (" name "), if (name! = null) {Out.print (" Hello "+ name);} else {out.print ("No paras");} %>
(3) Directly click to execute, or enter the URL in the browser, the results such as the following:
。
"Two" iosclient realization
(1) Create a new iOS project. Language Select Swift. Then design the interface in storyboard such as the following:
。
(2) Then bind the control and code separately. The input box TextField and the TextView that returns the result are outlets bound, and the button is sent to the action binding. The final implementation code such as the following:
@IBOutlet weak var inputname:uitextfield! @IBOutlet weak var feedbackinfo:uitextview! Override Func Viewdidload () { super.viewdidload () } @IBAction func connectserver (Sender:uibutton) { Nsurlconnection.sendasynchronousrequest (Nsurlrequest (Url:nsurl (string: "http://localhost:8080/MyServer/ Hello.jsp?name=\ (Inputname.text) "), Queue:nsoperationqueue ()) {(resp:nsurlresponse!, data:nsdata!, Error:NSError !) -void in IF-let D = data{ Dispatch_sync (Dispatch_get_main_queue (), {(), and void in self.feedbackinfo. Text = String (NSString (Data:d, Encoding:nsutf8stringencoding)})}}}}
The Click event of a button can also be in the following form:
@IBAction func ConnectServer (Sender:uibutton) { nsurlconnection.sendasynchronousrequest (nsurlrequest (URL: Nsurl (string: "Http://localhost:8080/MyServer/Hello.jsp?Name=\ (Inputname.text) "), Queue:NSOperationQueue.mainQueue ()) {(resp:nsurlresponse!, data:nsdata!, Error:nserror !) -Void in if let d = data{ Self.feedbackInfo.text = String (NSString (data:d, encoding:nsutf8stringencoding)! ) } } }
(3) Execution procedure. Implementation effects such as the following:
.
GitHub home: https://github.com/chenyufeng1991. Welcome to visit us!
iOS project development-communication with server via HTTP GET