iOS項目開發實戰——通過Http Get方式與server通訊

來源:互聯網
上載者:User

標籤:else   dba   分享   nbsp   operation   nts   輸入框   send   usr   

      移動client往往須要同後台server進行通訊,上傳或者下載資料,最經常使用到的方式就是Http Get,如今我們來學習在iOS項目中使用Get方式同server進行通訊。

【一】server端實現

(1)首先要安裝好能進行J2EE開發的Eclipse或者MyEclipse,配置好Tomcat環境。

我這裡使用Eclipse Mars。Tomcat版本號碼為8.  然後建立一個Dynamic Web Project。名稱為MyServer。

然後在WebContent中建立一個JSP File。名稱為index.當前檔案夾結構例如以下:


(2)然後在Hello.jsp中實現例如以下:對於client的請求,我將會返回“Hello 名字”。否則返回No Paras.

<%@ 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)直接點擊執行,或者在瀏覽器中輸入url,結果例如以下:


【二】iOSclient實現

(1)建立一個iOS項目。Language選擇Swift。然後在storyboard中設計介面例如以下:


(2)然後分別進行控制項和代碼的綁定。輸入框TextField和顯示返回結果的TextView進行Outlets綁定,發送button進行Action綁定。最後實現代碼例如以下:

        @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(), { () -> Void in                    self.feedbackInfo.text = String(NSString(data: d, encoding: NSUTF8StringEncoding)!)                })            }                    }    }


當中button的點擊事件也能夠是以下的形式:

    @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)執行程式。實現效果例如以下:

.


github首頁:https://github.com/chenyufeng1991  。歡迎大家訪問!


iOS項目開發實戰——通過Http Get方式與server通訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.