• iOS项目开发实战——通过Http Get方式与server通信


          移动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  。欢迎大家訪问!


  • 相关阅读:
    Process对象的其他属性:
    python网络编程之开启进程的方式
    python网络编程之进程论
    python网络编程之C/S架构介绍
    面向对象之元类介绍(未完待续)
    面向对象之继承
    面向对象之元类介绍
    python异常处理
    面向对象之内置方法
    面向对象之反射
  • 原文地址:https://www.cnblogs.com/jhcelue/p/6881363.html
Copyright © 2020-2023  润新知