[iOS swift]Get方式向服务器请求数据

时间:2022-08-22 17:56:43

//使用get的方式向服务器请求数据

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var mytext: UITextField!
@IBOutlet weak var outText: UITextView!
var na:NSString = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@IBAction func ClickToConnect(sender: AnyObject) {
//先将文本框内的字符赋给一个变量
na = mytext.text!
//url填入服务器的地址
NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: NSURL(string: "http://localhost:8080/MyServer/index.jsp?name=\(na)")!), queue: NSOperationQueue()) { (resp:NSURLResponse?, data:NSData?, error:NSError?) in

//完成之前的操作之后要找到主线程,要对UI在主线程进行修改
dispatch_sync(dispatch_get_main_queue(), {
self.outText.text = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
})

}


}

}


服务器端建立个jsp文件,代码如下

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<%
String str = request.getParameter("name");
if(str != ""){
out.print("Hello "+str);
}else{
out.print("No args");
}
%>