简单的http请求、URL编码

        //URL编码
        let origin = "徐乾"
        let encode = origin.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
        print(encode!)
        var path = "http://www.baidu.com?name=" + encode!
        let url = NSURL(string: path)
        print(url!)
        
        //NSURLConnection
        //创建一个数据请求任务
        path = "https://gitshell.com/wcrane/FM-Res/raw/blob/master/channels.json"
        let url1 = NSURL(string: path)
        let task = NSURLSession.sharedSession().dataTaskWithURL(url1!) { (data, response, error) in
            //data: 下载到的数据, NSData
            //response: 响应结果, status code以及header filed,
            //  NSURLResponse, NSHTTPURLResponse
            //error: 请求是否出错, 如果为nil, 请求没出错
            print("请求结果:\(data!.length)")
            if let e = error {
                //有错,网络连接失败
                print("请求错误: \(e)")
            }else{
                //没有错
                if let httpResponse = response as? NSHTTPURLResponse{
                    //服务器有响应
                    if httpResponse.statusCode == 404{
                        //404 Not Found,URL对应的资源不存在
                        print("404 Not Found")
                    }else if httpResponse.statusCode == 200{
                        //请求成功,获取到了数据
                        if let d = data{
                            //需要进一步处理
                            //将数据转换为UTF-8格式的字符串
                            let html = NSString(data: d, encoding: NSUTF8StringEncoding)
                            print(html!)
                        }
                    }
                }
            }
        }
        //开始执行
        task.resume()

你可能感兴趣的:(简单的http请求、URL编码)