无法在发布请求iOS Swift中发布参数

时间:2019-04-29 10:33:51

标签: ios swift xcode urlsession

我正在尝试将这些参数作为对URL的后期请求发送,但这些参数没有得到发送。我不知道URLSession是否是配置问题。谁能检查并解决问题?

import UIKit

let json: [String: Any] = [
    "set_id" : "20",
    "user_id" :  "30",
    "type" : "contact",
    "contact_name" : "shinto"
]

let jsonData = try? JSONSerialization.data(withJSONObject: json)

var str = String(data: jsonData!, encoding: .utf8)

let url = URL(string: "****.php")!
var request = URLRequest(url: url)

request.httpMethod = "Post"
request.httpBody = str!.data(using: .utf8)

let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) {

  (data, response, error) in
    if let data = data {
      if let postResponse = String(data: data, encoding: .utf8) {
        print(postResponse)
      }
    }

}
task.resume()

3 个答案:

答案 0 :(得分:1)

对此进行检查:

      func post method(){
      let headers = [
        "Content-Type": "application/json",
        "cache-control": "no-cache"]


    let parameters = ["set_id" : "20",
                      "user_id" :  "30",
                      "type" : "contact",
                      "contact_name" : "shinto"] as [String : Any]



    let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])

    let url = URL(string: "****.php")!
    var request = URLRequest(url: url)

    request.httpMethod = "POST"
    request.allHTTPHeaderFields = headers
    request.httpBody = postData as! Data

    let session = URLSession.shared
    let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
        if (error != nil) {
            print(error)
        }
        guard let httpresponse = response as? HTTPURLResponse,
            (200...299).contains(httpresponse.statusCode) else {
                print ("server error")
                return
        }


        if let mimeType = response?.mimeType,
            mimeType == "application/json",
            let data = data,
            let dataString = String(data: data, encoding: .utf8) {
            print ("got data: \(dataString)")

     }
     }
    })

    dataTask.resume()

}

答案 1 :(得分:1)

我使用了一个名为RequestBin的在线服务来检查您的请求,并且数据似乎已正确发送。正如评论中已经提到的,我只做了些微修改。

这是结果代码:

let json: [String: Any] = [
    "set_id" : "20",
    "user_id" :  "30",
    "type" : "contact",
    "contact_name" : "shinto"
]
let jsonData = try! JSONSerialization.data(withJSONObject: json)

let url = URL(string: "http://requestbin.fullcontact.com/***")! // Was "using"
var request = URLRequest(url: url)

request.httpMethod = "POST" // Was "Post"
request.httpBody = jsonData // Was utf8 string representation

let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) {
    (data, response, error) in
    if let data = data {
        if let postResponse = String(data: data, encoding: .utf8) {
            print(postResponse)
        }
    }

}
task.resume()

您可以使用this service检查检查结果。您只需创建一个新URL并在您的请求中使用它即可。成功发送请求后,您要做的就是重新加载页面以检查您的请求。

请注意,这些是“ http”请求,因此您需要允许arbitrary loads

答案 2 :(得分:0)

您可以按照以下方式设置请求,并根据需要更改内容类型

import UIKit    
let json: [String: Any]? = [
    "set_id" : "20",
    "user_id" :  "30",
    "type" : "contact",
    "contact_name" : "shinto"
]
let url = URL(string: "****.php")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
if let parameters = json
{
    self.makeParamterString(request: request, parameterDic: parameters)
}

let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) {

  (data, response, error) in
    if let data = data {
      if let postResponse = String(data: data, encoding: .utf8) {
        print(postResponse)
      }
    }

}
task.resume()
     static  func makeParamterString(request:NSMutableURLRequest, parameterDic:[String:AnyObject])
    {
        let _ =  NSCharacterSet(charactersIn:"=\"#%/<>?@\\^`{|}").inverted
        var dataString = String()
        for (key, value) in parameterDic {
            dataString = (dataString as String) + ("&\(key.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)=\(value)")
        }
        dataString = dataString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!
        request.httpBody = dataString.data(using: String.Encoding.utf8)
    }