swift直接传输json字串

客户端

//
//  ViewController.swift
//  http请求
//
//  Created by admin on 16/2/26.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.sendJSON()
    }
    func sendJSON()
    {
        let urlStr = "http://test.com/postjson.php"
        let url = NSURL(string: urlStr.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
        let request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: 10)
        let jsonData = ["name":"jin","age":18]
        // 检查数据类型是否能转换成json
        if NSJSONSerialization.isValidJSONObject(jsonData) == false
        {
            print("格式错误")
            exit(1)
        }
        let sendData = try? NSJSONSerialization.dataWithJSONObject(jsonData, options: NSJSONWritingOptions.PrettyPrinted)
        // 设置类型以及数据
        request.HTTPMethod = "post"
        request.HTTPBody = sendData
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (response:NSURLResponse?, data:NSData?, error:NSError?) -> Void in
            let jsonData:AnyObject? = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
            print(jsonData)
        }
    }
}

服务器

header('Content-Type:text/plain;charset=utf-8');

$json = file_get_contents('php://input');
// 反序列化JSON
$obj = json_decode($json, TRUE ); 

// 打印对象明细信息
echo json_encode($obj);

标签: swift, 网络

添加新评论