post请求 swift_swift post 请求 body - CSDN
  • 最近开始做新项目, 决定使用Swift 来做, 几个月前看了一下还是Swift2 现在已经到Swift3 了, 听说改动非常大。 那么直接从3学起吧,希望别出个4又改动非常大!   新做的项目会开始涉及到非常多的方面, 以前我是...

      最近开始做新项目, 决定使用Swift 来做, 几个月前看了一下还是Swift2  现在已经到Swift3 了, 听说改动非常大。 那么直接从3学起吧,希望别出个4又改动非常大! 

      新做的项目会开始涉及到非常多的方面, 以前我是用object-c的, 所以上手Swift可能会有些不适应。

      废话少说, 直接上代码:


    import UIKit
    
    
    /// 网络访问基类
    class BaseNetwrok: NSObject {
    
        
        /// Post 访问
        ///
        /// - Parameters:
        ///   - url: 服务器链接
        ///   - params: POST参数
        func post(url:String, params:NSMutableDictionary) {
            
            //创建会话对象
            let session     = URLSession.shared
            let serUrl      = URL(string:url)
            var request     = URLRequest(url: serUrl!)
            
            //设置访问方式为POST
            request.httpMethod = "POST"
            
            //设置POST 内容
            request.httpBody = getBody(params: params).data(using: String.Encoding.utf8)
            
            //开始访问
            let dataTask : URLSessionDataTask = session.dataTask(with: request) { (data, respones, error)  -> Void  in
                
                //访问结束
                if(error != nil) {
                    //返回出错
                    print(error.debugDescription)
                } else {
                    
                    //返回成功
                    let str = String(data: data!, encoding: String.Encoding.utf8)
                    
                    print(str ?? "error")
                }
                
            }
            dataTask.resume()
        }
        
        
        /// 获取post内容
        ///
        /// - Parameter params: 参数
        /// - Returns: Body
        func getBody(params:NSMutableDictionary) -> String {
            
            var body : String = "";
            
            for (key, value) in params {
                
                let str = "\(key)=\(value)&"
                
                body = body + str
            }
            
            if(body.characters.count > 1) {
                body = (body as NSString).substring(to: body.characters.count-1)
            }
            
            return body
        }
    }
    

    以上是一个非常普通, 非常简单的网络访问。 

    调用代码:

     let md = NSMutableDictionary()

     let a = BaseNetwrok()

      a.post(url: "http://www.baidu.com", params: md)


    待后续会上传更复杂的访问方式。


    展开全文
  • 网络请求一定是其中的重头戏,Object-C的网络请求大家都不陌生,不过感觉很熟悉的貌似也不多,因为第三方的库用起来更加方便,比如我们所熟知的AFNetworking,在Swift中,也存在一些封装的比较好的网络请求库,...

    只要属于移动开发的范畴,网络请求一定是其中的重头戏,Object-C的网络请求大家都不陌生,不过感觉很熟悉的貌似也不多,因为第三方的库用起来更加方便,比如我们所熟知的AFNetworking,在Swift中,也存在一些封装的比较好的网络请求库,不过我今天说的不是那种第三方的,而是原生的请求方法,下面看代码:

    import UIKit
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
    
    
            let getBtn = UIButton(type: .System)
            getBtn.frame = CGRectMake(50, 100, 100, 100)
            getBtn.setTitle("GET", forState: .Normal)
            getBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)
            getBtn.addTarget(self, action: #selector(self.GETACtion), forControlEvents: .TouchUpInside)
            self.view.addSubview(getBtn)
    
    
            let postBtn = UIButton(type: .System)
            postBtn.frame = CGRectMake(self.view.frame.size.width - 150, 100, 100, 100)
            postBtn.setTitle("POST", forState: .Normal)
            postBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)
            postBtn.addTarget(self, action: #selector(self.POSTACtion), forControlEvents: .TouchUpInside)
            self.view.addSubview(postBtn)
    
        }
    
        /**
         往下看你会发现其实GET和POST差不多是一样的,一般我们认为GET方法是不用上传参数的,所有的参数都在请求链接中或者索性直接没参数,在这里GET方法中你看到参数是可以放在请求体中的,而大多数搜索到的区别都认为GET的参数在请求链接上,这种说法是不对的,GET参数完全可以放在请求体中,并不是因为GET连接长度有限制,起到限制的不是http协议,而是服务器和浏览器,所以乍一看这里GET和POST几乎一样,但它们在HTTPMethod是有着本质区别的,不再说本质区别,有兴趣的自己了解。
    
    
         另外需要注意的是,这里的字典,如果你想封装的话一定要考虑字典为空的情况,如果为空,请不要使用    
         request.HTTPMethod = "XXX",否则会报错,所以,如你所见,当字典为空时,POST和GET没有任何区别,但至于它属于什么方法,我并没有从网上找到答案,留待大家补充
    
         */
    
    
    
    
    
        /**
         GET请求
         */
        func GETACtion() {
            //请求URL
            let url:NSURL! = NSURL(string: "http://iappfree.candou.com:8080/free/applications/limited")
            let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
            let list  = NSMutableArray()
            var paramDic = [String: String]()
    
            if paramDic.count > 0 {
                //设置为GET请求
                request.HTTPMethod = "GET"
                //拆分字典,subDic是其中一项,将key与value变成字符串
                for subDic in paramDic {
                    let tmpStr = "\(subDic.0)=\(subDic.1)"
                    list.addObject(tmpStr)
                }
                //用&拼接变成字符串的字典各项
                let paramStr = list.componentsJoinedByString("&")
                //UTF8转码,防止汉字符号引起的非法网址
                let paraData = paramStr.dataUsingEncoding(NSUTF8StringEncoding)
                //设置请求体
                request.HTTPBody = paraData
            }
            //默认session配置
            let config = NSURLSessionConfiguration.defaultSessionConfiguration()
            let session = NSURLSession(configuration: config)
            //发起请求
            let dataTask = session.dataTaskWithRequest(request) { (data, response, error) in
    
                //            let str:String! = String(data: data!, encoding: NSUTF8StringEncoding)
                //            print("str:\(str)")
                //转Json
                let jsonData:NSDictionary = try! NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary
    
                print(jsonData)
    
            }
            //请求开始
            dataTask.resume()
    
        }
        /**
         POST请求
         */
        func POSTACtion() {
            //请求URL
            let url:NSURL! = NSURL(string: "http://iappfree.candou.com:8080/free/applications/limited")
            let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
            let list  = NSMutableArray()
            var paramDic = [String: String]()
    
            if paramDic.count > 0 {
                //设置为POST请求
                request.HTTPMethod = "POST"
                //拆分字典,subDic是其中一项,将key与value变成字符串
                for subDic in paramDic {
                    let tmpStr = "\(subDic.0)=\(subDic.1)"
                    list.addObject(tmpStr)
                }
                //用&拼接变成字符串的字典各项
                let paramStr = list.componentsJoinedByString("&")
                //UTF8转码,防止汉字符号引起的非法网址
                let paraData = paramStr.dataUsingEncoding(NSUTF8StringEncoding)
                //设置请求体
                request.HTTPBody = paraData
            }
            //默认session配置
            let config = NSURLSessionConfiguration.defaultSessionConfiguration()
            let session = NSURLSession(configuration: config)
            //发起请求
            let dataTask = session.dataTaskWithRequest(request) { (data, response, error) in
    
                //            let str:String! = String(data: data!, encoding: NSUTF8StringEncoding)
                //            print("str:\(str)")
                //转Json
                let jsonData:NSDictionary = try! NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary
    
                print(jsonData)
    
            }
            //请求开始
            dataTask.resume()
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
    
    }
    

    下载地址

    展开全文
  • swift2.0 异步post请求

    2016-04-17 15:43:23
    swift语言实现异步网络post请求,用NSDictionary封装post表单。 class func post(urlString urlString: String?,postParams: NSDictionary!,completion: (data: NSString?) -> Void){ if urlString == nil { dis

    swift语言实现异步网络post请求,用NSDictionary封装post表单。

    class func post(urlString urlString: String?,postParams: NSDictionary!,completion: (data: NSString?) -> Void){
            if urlString == nil {
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    print("urlString 为空")
                    completion(data: nil)
                })
            }
            
            let url = NSURL(string: urlString!)//post的url地址
            let request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 10)
            request.HTTPMethod = "POST"
            parseParams(Params: postParams, completion: {(result) in
                let postData: NSData = (result?.dataUsingEncoding(NSUTF8StringEncoding))!
                request.HTTPBody = postData//post表单
            })
            let queue = NSOperationQueue()
            NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler: {
                (response,data,error) -> Void in
                let httpResponse = response as? NSHTTPURLResponse
                if httpResponse?.statusCode == 200{
                    let parseData = NSString(data: data!, encoding: NSUTF8StringEncoding)//self.parseJSONData(data)
                    dispatch_async(dispatch_get_main_queue(),{
                        () -> Void in
                        completion(data: parseData)
                    })
                }else {
                    dispatch_async(dispatch_get_main_queue(), {
                        () -> Void in
                        print(error)
                        completion(data: nil)
                    })
                }
            })
        }
    当然在post之前还要将传过来的NSDictionary转化为post的固定格式

    class func parseParams(Params Params: NSDictionary!,completion: (paramString: NSString?) -> Void){
            var keyValueFormat: String?
            let result = NSMutableString()
            let keyEnum = Params.keyEnumerator()
            while let key = keyEnum.nextObject() as? String{
                keyValueFormat = String.init(format: "%@=%@&", arguments: [key,(Params.valueForKey(key)?.description)!])//post的键值对
                result.appendString(keyValueFormat!)
            }
            completion(paramString: result)
        }


    展开全文
  • <div class="post-text" itemprop="text"> <p>I´m trying to send data to a PHP file on my server using <code>URLSession</code>. This seems to fail though, since no data is received on the server. ...
  • swift5向服务器发送请求 Xcode版本:11.1 配置HTTPS Xcode只能用https不能http 先给Spring Boot工程配置https https://www.cnblogs.com/sufferingStriver/p/9026902.html 生成证书丢到resources文件夹中 ...

    继续上一篇
    用swift5向服务器发送请求
    Xcode版本:11.1

    配置HTTPS

    Xcode只能用https不能http
    先给Spring Boot工程配置https

    https://www.cnblogs.com/sufferingStriver/p/9026902.html

    生成证书丢到resources文件夹中
    application.properties中增加属性

    # SSL config
    server.ssl.key-store = classpath:证书文件名
    server.ssl.key-store-password = 证书密码
    

    改一下version为0.0.2丢到服务器上

    Swift发送POST请求

    新建Xcode工程(此处用的storyboard没用swiftUI)
    图片丢进Assets.xcassets
    新建类

    //
    //  PostImage.swift
    //  PostImage
    //
    //  Created by S Xu on 2019/10/22.
    //  Copyright © 2019 S Xu. All rights reserved.
    //
    
    import Foundation
    
    class PostImage {
        
        var msg : String?
        
        func post(name:String,imageBase64:String,completion: @escaping (String?) -> ()) {
            
            // 请求地址
            let url = "https://coconutnut.xyz:2222/image"
            
            // 设置请求参数
            var request = URLRequest(url: URL(string: url)!)
            request.httpMethod = "POST"
            request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
            
            // 填入json数据
            let json = ["name":name,"imageBase64":imageBase64] as [String : Any]
            let jsonData = try? JSONSerialization.data(withJSONObject: json)
            
            // 装入request
            request.httpBody = jsonData
            
            // 发送请求
            let task = URLSession.shared.dataTask(with: request) { (data:Data?, response:URLResponse?, error:Error?) in
                
                // 处理返回数据
                if let data = data {
                        
                    do {
                        
                            if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] {
                                
                                // 获取msg
                                if let result = json["msg"] as? String{
                                
                                    self.msg = result
                                    print("GET MSG:",self.msg)
                                    
                                }
                            }
                        
                        }catch {
                            print(error.localizedDescription)
                        }
                        
                    completion(self.msg)
                        
                    }
                    
                }
            
            task.resume()
            
        }
        
    }
    

    随便找个地方调一下
    这里就扔在ViewController的viewDidLoad()里了

    //
    //  ViewController.swift
    //  PostImage
    //
    //  Created by S Xu on 2019/10/22.
    //  Copyright © 2019 S Xu. All rights reserved.
    //
    
    import UIKit
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
            
            // 获取图片
            let image = UIImage(named: "yeeeeeeeah")
            
            // 将图片转化成base64字符串
            let imageData = image!.pngData()
            let base64 = imageData?.base64EncodedString()
                   
            print("-----------发送POST请求-----------")
            let postImage = PostImage()
            postImage.post(name: "testImage", imageBase64: base64!, completion: { (results:String?) in
                       
                print("-----------获取POST结果-----------")
                print(results)
                       
            })
        }
    
    }
    

    运行结果

    展开全文
  • 基于AFNetworking3.0 封装的GET和POST请求 上传 下载
  • IOS 原生网络请求 swift

    2019-10-18 11:22:41
    初次学习。 import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? ... func application(_ application: UIApplication, didFinishLaunchingWithOp...

    初次学习。

    
    import UIKit
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        var window: UIWindow?
    
    
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
            NSLog("@","application" );
            requestSwift();
            var alertView = UIAlertView();
            alertView.delegate=self;
            alertView.title = "Title";
            alertView.message = "Message";
            alertView.addButton(withTitle: "OK");
            alertView.show() ;
            // Override point for customization after application launch.
            return true
        }
    
        func applicationWillResignActive(_ application: UIApplication) {
            // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
            // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
            
        }
    
        func applicationDidEnterBackground(_ application: UIApplication) {
            // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
            // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        }
    
        func applicationWillEnterForeground(_ application: UIApplication) {
            // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
        }
    
        func applicationDidBecomeActive(_ application: UIApplication) {
            // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        }
    
        func applicationWillTerminate(_ application: UIApplication) {
            NSLog("asdsad", "applicationWillTerminate");
            // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        }
        //网络请求
        func requestSwift(){
            let url = URL(string: "https://api.map.baidu.com/place/v2/search?query=%E9%93%B6%E8%A1%8C&region=%E9%83%91%E5%B7%9E&output=json&ak=6E823f587c95f0148c19993539b99295")
            var request = URLRequest(url: url!)
            request.httpMethod = "GET"
            let configuration:URLSessionConfiguration = URLSessionConfiguration.default
            let session:URLSession = URLSession(configuration: configuration)
            let task:URLSessionDataTask = session.dataTask(with: request) { (data, response, error)->Void in
                if error == nil{
                    do{
           let responseData:NSDictionary = try JSONSerialization.jsonObject(with: data!, options:   JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
                        print("response:\(response)")
                        print("responseData:\(responseData)")
              }catch{
                        print("catch")        
                    }
                }else{     
                    print("error:\(error)")     
                }
            }
            task.resume()
            
        }
        
    
    
    
    }
    
    
    
    
    展开全文
  • 说明:本文示例代码发送的请求均为http请求,需要对info.plist文件进行配置。如何配置,请参考https://github.com/HanGangAndHanMeimei/iOS9AdaptationTips 一、简单说明  在iOS9.0之后,以前使用的...
  • WKWebView之POST请求

    2018-09-05 15:09:01
    WKWebView之POST请求 WKWebView是不兼容POST请求的,我们可以重写loadRequest实现POST请求。 //重写load方法,使用runtime替换掉WKWebView的loadRequest方法; + (void)load { static dispatch_once_t ...
  • AFNETWORKING SWIFT

    2018-08-24 23:33:15
            import UIKit   class ViewController: UIViewController,UITableViewDataSource {      var newsArr:[News] = [News] ()  var table : UITableView?   ... f...
  • swift3.0请求https封装工具类(get请求和post请求)
  • var url:String="http://******"  var roomDic=DictionaryString,String>()  roomDic["roomId"]=“fff”  roomDic["roomPassword"]="123456" ...post(url,roomDic) ...func post(url:String,para
  • 在Object-C中AFNetworking几乎是我们不可或缺的第三方库,使用起来非常方便,在Swift中,Alamofire是对应AFNetworking的第三方库,使用方法完全一样,下面看看常用的GET和POST怎么来写的: func loadData() { ...
  • 1.首先工具类内部需要遵守URLSessionDataDelegate代理 2.实现代理方法代码如下:  func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: ...
  • get 和 post 请求有哪些区别? 1、从主流浏览器的实现角度看 下面的对比表格摘自:w3school --HTTP 方法:GET 对比 POST GET POST 后退按钮/刷新 无害 数据会被重新提交(浏览器应该告知用户数据...
  • Swift使用Swift调用AFNetworking进行网络请求  如何使用Swift进行网络请求呢? 我们首先创建一个Swift工程,工程名是SwiftDemo 然后在该工程中新建一个 Oc的类,那么Xcode会询问你是否创建 桥接 Oc和 Swift的 ...
  •  所有网络请求,统一使用异步请求!    在今后的开发中,如果使用简单的get/head请求,可以用NSURLConnction异步方法  GET查/POST增/PUT改/DELETE删/HEAD    GET  1> URL  2> NSURLRequest  3
  • iOS.Swift使用 POST请求

    2019-02-17 18:54:40
    URLService       import UIKit ...class URLService: NSObject { ... func POST(url:String,pass:@escaping (Any,Bool)-&gt;Void) {  let urlStr = URL.init(string: "http://api.jisuapi.com/ill...
  • 一、GET请求和POST请求简单说明  @IBOutlet weak var userName: UITextField!  @IBOutlet weak var userPwd: UITextField!  @IBOutlet weak var logonResult: UILabel!   /* 创建Get请求 */
  • 转载地址:http://blog.csdn.net/abcd2686529828/article/details/51323673说明:本文示例代码发送的请求均为http请求,需要对info.plist文件进行配置。如何配置,请参考...
1 2 3 4 5 ... 20
收藏数 3,707
精华内容 1,482
关键字:

post请求 swift