swift4--利用Alamofire发起网络请求

先推荐一个好用的第三方库Alamofire

下载地址:https//github.com/Alamofire/Alamofire

下载Alamofire后把xcodeproj文件拖进去,然后如图配置

导入Alamofire:

添加测试代码

import UIKit
//调用一下刚添加的库文件
import Alamofire
//通过同步post请求,同步获取IP地址信息
class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let lable = UILabel()
        lable.frame = CGRect(x: 20, y: 40, width: 280, height: 500)
        lable.text = "loading..."
        lable.font = UIFont(name: "Arial", size: 12)
        lable.backgroundColor = UIColor.lightGray
        lable.numberOfLines = 0
        //        换行时保留所有字符
        lable.lineBreakMode = NSLineBreakMode.byWordWrapping
        self.view.addSubview(lable)
        Alamofire.request("https://c.y.qq.com/v8/fcg-bin/fcg_v8_toplist_cp.fcg?g_tk=5381&uin=0&format=json&inCharset=utf-8&outCharset=utf-8&notice=0&platform=h5&needNewCode=1&tpl=3&page=detail&type=top&topid=27&_=1519963122923").responseJSON { response in
                        print("Request: \(String(describing: response.request))")   // 原始url请求
                        print("Response: \(String(describing: response.response))") // http url响应
                        print("Result: \(response.result)")                         // 响应序列化结果
            
            if let json = response.result.value {
                print("JSON: \(json)") // 序列化json响应
                
            }
            
            if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
                print("Data: \(utf8Text)") // 原始服务器数据为UTF8字符串
                lable.text = utf8Text
            }
        }

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

查看模拟器上输出的请求内容

猜你喜欢

转载自blog.csdn.net/weixin_41735943/article/details/81813449