如何将其转换为带有JSON序列化对象的POST调用对象

问题描述:

我试过Alamofire,我已尽全力尝试过它。它只是不适合我。我终于得到了http GET的工作,但我需要让http POST工作。我们的POST API接受一个Request对象,它具有所有必要的数据。我已经要求后端开发人员为我提供一个KEY-VALUE对JSON(没有嵌入的对象/数组),以便我可以在我的swift代码中使用字典将其转换为json并发送请求。我需要的是将下面的代码转换为POST。如何将其转换为带有JSON序列化对象的POST调用对象

我以前的问题没有多大帮助。 NSInvalidArgumentException Invalid type in JSON write DemographicsPojo Swift 3.0, Alamofire 4.0 Extra argument 'method' in call

我放弃了Alamofire。我想要使​​用基础课程。简单的基本和基本的生活方式:)。

func callWebService(url : String) { 
     // Show MBProgressHUD Here 
     var config        :URLSessionConfiguration! 
     var urlSession       :URLSession! 

     config = URLSessionConfiguration.default 
     urlSession = URLSession(configuration: config) 

     // MARK:- HeaderField 
     let HTTPHeaderField_ContentType   = "Content-Type" 

     // MARK:- ContentType 
     let ContentType_ApplicationJson   = "application/json" 

     //MARK: HTTPMethod 
     let HTTPMethod_Get      = "GET" 

     let callURL = URL.init(string: url) 

     var request = URLRequest.init(url: callURL!) 

     request.timeoutInterval = 60.0 // TimeoutInterval in Second 
     request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData 
     request.addValue(ContentType_ApplicationJson, forHTTPHeaderField: HTTPHeaderField_ContentType) 
     request.httpMethod = HTTPMethod_Get 

     let dataTask = urlSession.dataTask(with: request) { (data,response,error) in 
      if error != nil{ 
       print("Error **") 

       return 
      } 
      do { 
       let resultJson = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject] 
       print("Result",resultJson!) 
      } catch { 
       print("Error -> \(error)") 
      } 
     } 

     dataTask.resume() 
     print("..In Background..") 
    } 
+0

我有点困惑,你要求重写代码发送POST请求?请尝试通过你自己,而不是如果它不工作寻求帮助。 –

+0

相信我,当我说这个,我已经尝试过,失败了。我终于有一个工作的GET,但不能让POST工作。 – Siddharth

只需将JSON字符串和API URL传递给此函数即可。完整的POST代码。

func POST(api:String,jsonString:String,completionHandler:@escaping (_ success:Bool,_ response:String?,_ httpResponseStatusCode:Int?) -> Void) { 

    let url = URL(string: api) 

    var request: URLRequest = URLRequest(url: url!) 

    request.httpMethod = "POST" 

    request.setValue("application/json", forHTTPHeaderField:"Content-Type") 
    request.timeoutInterval = 60.0 

    //additional headers 
    if let token = Helper.readAccessToken() { 
     request.setValue("\(token)", forHTTPHeaderField: "Authorization") 
    } 

    let jsonData = jsonString.data(using: String.Encoding.utf8, allowLossyConversion: true) 
    request.httpBody = jsonData 

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

     var responseCode = 0 
     if let httpResponse = response as? HTTPURLResponse { 
      responseCode = httpResponse.statusCode 
      print("responseCode \(httpResponse.statusCode)") 
     } 

     if error != nil { 
      completionHandler(false, error?.localizedDescription,nil) 

     } else { 
      let responseString = String(data: data!, encoding: .utf8) 
      completionHandler(true, responseString, responseCode) 
     } 
    } 

    task.resume() 
}