如何使用swift将Json作为参数发送到url中

时间:2015-04-27 12:10:47

标签: ios swift nsurlconnection swifty-json

我是快速语言的新手。我在这里看了一些关于在swift中解析Json的问题,但是我的问题与其他问题有些不同。 当我写/ cmd = login& params {' user':' username',' password':' pass'}它返回正确的数据。如何在swift中解决这个问题 我将用户名和密码作为json发送给url但是 它检索错误,这意味着"格式无效" 请帮我。 这是我尝试过的:

  var url:NSURL = NSURL(string: "http://<host>?cmd=login")!
    //var session = NSURLSession.sharedSession()
    var responseError: NSError?


    var request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)

    // var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
    var response: NSURLResponse?
    request.HTTPMethod = "POST"

let jsonString = "params={\"user\":\"username\",\"password\":\"pass\"}"

    request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion:true)
    request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")

    // send the request
    NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &responseError)

    // look at the response
    if let httpResponse = response as? NSHTTPURLResponse {
        println("HTTP response: \(httpResponse.statusCode)")
    } else {
        println("No HTTP response")
    }
    let task  = NSURLSession.sharedSession().dataTaskWithRequest(request){
        data, response, error in
        if error != nil {
            println("error=\(error)")
            return
        }

        println("****response= \(response)")
        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("**** response =\(responseString)")
        var err: NSError?
        var json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers , error: &err) as? NSDictionary

    }
    task.resume()

4 个答案:

答案 0 :(得分:4)

根据您的问题假设服务器期望的格式是这样的:

http://<host>?cmd=login&params=<JSON object>

在将JSON对象附加到查询字符串之前,您需要首先URL-encode以消除任何非法字符。

您可以这样做:

let jsonString = "{\"user\":\"username\",\"password\":\"pass\"}"
let urlEncoadedJson = jsonString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
let url = NSURL(string:"http://<host>?cmd=login&params=\(urlEncoadedJson)")

答案 1 :(得分:0)

你的json字符串无效,应该是:

let jsonString = "{\"user\":\"username\",\"password\":\"pass\"}"

至于请求,我认为GET是你真正需要的:

var urlString = "http://<host>" // Only the host
let payload = "?cmd=login&params=" + jsonString // params goes here
urlString += payload
var url:NSURL = NSURL(string: urlString)! 
// ...
request.HTTPMethod = "GET"

答案 2 :(得分:0)

让我们说url是

https://example.com/example.php?Name=abc&data= {&#34;类&#34;:&#34; 625&#34;&#34受试者#34;:&#34;英语&#34;}

在Swift 4中

let abc = "abc"
let class = "625"
let subject = "english"



let baseurl = "https://example.com/example.php?"

let myurlwithparams = "Name=\(abc)" + "&data=" +

"{\"class\":\"\(class)\",\"subject\":\"\(subject)\"}"

let encoded = 
myurlwithparams.addingPercentEncoding(withAllowedCharacters: 
.urlFragmentAllowed)

let encodedurl = URL(string: encoded!)

var request = URLRequest(url: encodedurl!)

request.httpMethod = "GET"

答案 3 :(得分:-1)

我认为您不需要按照自己的方式对JSON进行编码。下面应该有用。

let jsonString = "params={\"user\":\"username\",\"password\":\"pass\"}"
var url:NSURL = NSURL(string: "http://<host>?cmd=login&?\(jsonString)")!
//var session = NSURLSession.sharedSession()
var responseError: NSError?


var request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)

// var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
var response: NSURLResponse?
request.HTTPMethod = "POST"