使用url的datatask工作正常,而使用request调用datatask则返回带有垃圾的数据

时间:2022-10-07 17:33:55

I am invoking a webservice using URLSession.shared.dataTask. Invoking it with, datatask with url works fine whereas calling datatask with request returns data with "garbage at the end". Can someone explain me why? Following is the function in 2 formats.

我正在使用URLSession.shared.dataTask调用Web服务。使用带有url的datatask调用它可以正常工作,而使用请求调用datatask会返回带有“最后的垃圾”的数据。有人能解释我为什么吗?以下是2种格式的功能。

dataTask called with URL (task = URLSession.shared.dataTask(with: url, completionHandler) works fine and returns valid results in data.

使用URL调用dataTask(task = URLSession.shared.dataTask(with:url,completionHandler)正常工作并返回数据中的有效结果。

basePath is The path of the web service URL

basePath是Web服务URL的路径

static func getUserDetails(withprefixText prefixText: String, withUserName userName:String, withPassword password:String) {
    // Call the web serrvice
urlString = basePath + "?prefixText=" + prefixText + "&prefixText1=" + userName + "&prefixText2=" + password
    guard let url = URL(string: urlString) else { return }

    let task = URLSession.shared.dataTask(with: url, completionHandler: { (data: Data?,response: URLResponse?,error: Error?) in

    if error != nil {
            print("error = \(String(describing: error))")
            return
        }
        //Let's convert response sent from a server side script to a NSDictionary object:
        do {
            let json = try JSONSerialization.jsonObject(with: data! , options: []) as? [String:Any]
            if let parseJSON = json {
                if let data = parseJSON["data"] as? [[String:Any]] {
        Now we can access values by it's key
                }
            }
            else {
                print ("Parsing error")
            }
        } catch {
            print("Serilization Error = \(error)")
        }
    })
    task.resume()
}

dataTask called with request (task = URLSession.shared.dataTask(with: request, completionHandler) returns results in data with garbage at end. So JSONSerialization.jsonObject fails with the error "Garbage at end"

使用request调用dataTask(task = URLSession.shared.dataTask(with:request,completionHandler)返回带有垃圾的数据结果。所以JSONSerialization.jsonObject失败并显示错误“Garbage at end”

static func getUserDetails(withprefixText prefixText: String, withUserName userName:String, withPassword password:String) {
    // Call the web serrvice
    let myURL = URL(string: basePath)
    var request = URLRequest(url: myURL!)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")

    let postString = ["prefixText": prefixText, "prefixText1": userName, "prefixText2": password] as [String: String]
    if JSONSerialization.isValidJSONObject(postString) {
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: postString, options: .prettyPrinted)
        }
        catch let error {
            print(error.localizedDescription)
            return
        }
    }

    let task = URLSession.shared.dataTask(with: request, completionHandler: { (data: Data?,response: URLResponse?,error: Error?) in

    if error != nil {
            print("error = \(String(describing: error))")
            return
        }
        do {
            let json = try JSONSerialization.jsonObject(with: data! , options: []) as? [String:Any]
            if let parseJSON = json {
                if let data = parseJSON["data"] as? [[String:Any]] {
                        // Now we can access values by its key
                }

            }
            else {
                print ("Parsing error")
            }
        } catch {
            print("Serilization Error = \(error)")
        }
    })
    task.resume()
}

1 个解决方案

#1


0  

Your webservice take paramter as URLencoding

您的网络服务作为URLencoding参与

so content type should be

所以内容类型应该是

"Content-Type" : "application/x-www-form-urlencoded"

“内容类型”:“application / x-www-form-urlencoded”

You can do it like this

你可以这样做

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.HTTPAdditionalHeaders = [
    "Accept" : "application/json",
    "Content-Type" : "application/x-www-form-urlencoded"
]

let session = NSURLSession(configuration: config)

let request = NSMutableURLRequest(URL: NSURL(string:"BASE_URL_SERVER")!)

// this paramter as example just set your paramter
request.encodeParameters(["name" : "email@email.com", "passwordd":"password"])

let task = session.dataTaskWithRequest(request) { data, response, error in
    guard error == nil && data != nil else {
        print(error)
        return
    }
    // now you can use data to serialize it

}
task.resume()

#1


0  

Your webservice take paramter as URLencoding

您的网络服务作为URLencoding参与

so content type should be

所以内容类型应该是

"Content-Type" : "application/x-www-form-urlencoded"

“内容类型”:“application / x-www-form-urlencoded”

You can do it like this

你可以这样做

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.HTTPAdditionalHeaders = [
    "Accept" : "application/json",
    "Content-Type" : "application/x-www-form-urlencoded"
]

let session = NSURLSession(configuration: config)

let request = NSMutableURLRequest(URL: NSURL(string:"BASE_URL_SERVER")!)

// this paramter as example just set your paramter
request.encodeParameters(["name" : "email@email.com", "passwordd":"password"])

let task = session.dataTaskWithRequest(request) { data, response, error in
    guard error == nil && data != nil else {
        print(error)
        return
    }
    // now you can use data to serialize it

}
task.resume()