1

我是 Swift 语言的新手。我在这里查看了一些用于快速解析 Json 的问题,但我的问题与其他问题略有不同。当我写 /cmd=login¶ms{'user':'username','password':'pass'} 它返回正确的数据。如何快速解决这个问题我将用户名和密码作为 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

4 回答 4

5

Assuming based on your question that the format the server is expecting is something like this:

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

You would need to first URL-encode the JSON object before appending it to the query string to eliminate any illegal characters.

You can do something like this:

let jsonString = "{\"user\":\"username\",\"password\":\"pass\"}"
let urlEncoadedJson = jsonString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
let url = NSURL(string:"http://<host>?cmd=login&params=\(urlEncoadedJson)")
于 2015-04-27T12:36:25.017 回答
2

假设 url 是

https://example.com/example.php?Name=abc&data= {"class":"625","subject":"english"}

在斯威夫特 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"
于 2018-02-15T07:15:11.543 回答
-1

你的 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"
于 2015-04-27T12:15:31.607 回答
-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"
于 2015-04-27T12:21:37.227 回答