2017-07-19 489 views
1

我曾嘗試使用以下代碼來處理請求,但結果爲400錯誤。 API由標題和正文組成。標題有兩個字段,即「授權」和「內容類型」。正文格式被添加到下面的參數。如何在Alamofire中請求帶有body和header的JSON?

enter image description here

enter image description here

func file(sender: abc){ 

     let baseUrl = "url」 

     let params: [String : Any] = [ 
      "profile": [ 
       「Type": [ 
        " Real Estate", 
        "Estater", 
        "Construction", 
        "Entertainment" 
       ], 
       "Size": [ 
        "large", 
        「small」 
       ], 
       "Level": [ 
        「A」, 
        「B」 
       ], 
       「Name」 : [ 
        「John」, 
        「Harry」 
       ] 
      ] 
     ] 

     let header = [ 
      "Authorization" : "bearer e2ff3aa3-63a3-41d1-bc5a-3e8c88adeaaa", 
      "Content-Type" : "application/json" 
     ] 

//  var request = URLRequest(url: URL(string:baseUrl)!) 
//  request.httpMethod = HTTPMethod.post.rawValue 
//  request.setValue("application/json", forHTTPHeaderField: "Content-Type") 
//  request.addValue("bearer e2ff3aa3-63a3-41d1-bc5a-3e8c88adeaaa", forHTTPHeaderField: "Authorization") 
//  let data = try! JSONSerialization.data(withJSONObject: params as Any, options:JSONSerialization.WritingOptions.prettyPrinted) 
//   
//  request.httpBody = data 

     Alamofire.request("\(baseUrl)", method: .post, parameters: params, headers:header).responseJSON { response in 
      print(response.request ?? "no request") // original URL requ est 
      print(response.response ?? "no response") // HTTP URL response 
      print(response.data ?? "no data")  // server data 
      print(response.result) // result of response serialization 
      print(response.response?.statusCode ?? "noCode") 

      if(response.response?.statusCode != nil){ 
       switch response.response!.statusCode { 
       case 200: 
        print("Success") 
        let json = JSON(data: response.data!) 
        print(json) 
        sender.onSuccessCall() 
       case 400: 
        print("Error in authentication") 
       case 401: 
        print("Error authentication object was not found") 
       default: 
        print("dEfault") 
       } 
      } 
     } 
    } 

請幫助解決售後服務這個問題。

+1

,我們不知道你的API希望你在做什麼你的工作 –

+0

我只是想通過POST請求JSON數據,但它說400錯誤。我的代碼中有任何錯誤嗎? –

+1

不知道你的API期望什麼,我們不能幫助。請包括一個成功的請求在你的問題,即使它不是從迅速(即郵遞員請求,捲曲請求等)。 –

回答

0

有時我們需要URLEncoding.httpBody類型POST方法希望它可以幫助你在的baseUrl

let headers = [ 
        // "Content-Type": "application/x-www-form-urlencoded" // try this if its ok then use this otherwise use "application/json" 
        // "Content-Type" : "application/json" 
       ] 
      let parameters = [ 

       ] 

      Alamofire.request("urlString", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).responseJSON { (response:DataResponse<Any>) in 

       switch(response.result) { 
       case.success(let data): 
        print("success",data) 
       case.failure(let error): 
        print("Not Success",error) 
        self.view.makeToast(message: "Server Error!!") 
       } 

      } 
+0

謝謝@Bikesh Thakur,但它不起作用這裏。 –

+0

你得到了什麼錯誤 –

+0

,你是否把「授權」:「承載e2ff3aa3-63a3-41d1-bc5a-3e8c88adeaaa」在內容類型的標題,並試過這 –

0

使用URLConvertible輸入url

解決方案低於:

func file(sender: abc){ 

     let baseU = URL(string:"url") 
     let baseUrl = baseU as! URLConvertible 

     let params: [String : Any] = [ 
      "profile": [ 
       "Type": [ 
       " Real Estate", 
       "Estater", 
       "Construction", 
       "Entertainment" 
       ], 
       "Size": [ 
       "large", 
       "small" 
       ], 
       "Level": [ 
       "A", 
       "B" 
       ], 
       "Name" : [ 
       "John", 
       "Harry" 
       ] 
      ] 
     ] 

     let header = [ 
      "Authorization" : "bearer e2ff3aa3-63a3-41d1-bc5a-3e8c88adeaaa", 
      "Content-Type" : "application/json" 
     ] 

     //  var request = URLRequest(url: URL(string:baseUrl)!) 
     //  request.httpMethod = HTTPMethod.post.rawValue 
     //  request.setValue("application/json", forHTTPHeaderField: "Content-Type") 
     //  request.addValue("bearer e2ff3aa3-63a3-41d1-bc5a-3e8c88adeaaa", forHTTPHeaderField: "Authorization") 
     //  let data = try! JSONSerialization.data(withJSONObject: params as Any, options:JSONSerialization.WritingOptions.prettyPrinted) 
     // 
     //  request.httpBody = data 

     Alamofire.request(baseUrl, method: .post, parameters: params, headers:header).responseJSON { response in 
      print(response.request ?? "no request") // original URL requ est 
      print(response.response ?? "no response") // HTTP URL response 
      print(response.data ?? "no data")  // server data 
      print(response.result) // result of response serialization 
      print(response.response?.statusCode ?? "noCode") 

      if(response.response?.statusCode != nil){ 
       switch response.response!.statusCode { 
       case 200: 
        print("Success") 
        let json = JSON(data: response.data!) 
        print(json) 
        sender.onSuccessCall() 
       case 400: 
        print("Error in authentication") 
       case 401: 
        print("Error authentication object was not found") 
       default: 
        print("dEfault") 
       } 
      } 
     } 
} 
+0

謝謝,@Sakir Sherasiya。我試試它,但不起作用。 –

+0

你得到了什麼錯誤 –

+0

它顯示了400狀態碼 –

1

我解決了這個問題,下面添加了正確的方法。

func file(sender: abc){ 

    let params: [String : Any] = [ 
     "profile": [ 
      「Type": [ 
       " Real Estate", 
       "Estater", 
       "Construction", 
       "Entertainment" 
      ], 
      "Size": [ 
       "large", 
       「small」 
      ], 
      "Level": [ 
       「A」, 
       「B」 
      ], 
      「Name」 : [ 
       「John」, 
       「Harry」 
      ] 
     ] 
    ] 

var request = URLRequest(url: URL(string:」url string」)!) 
    request.httpMethod = HTTPMethod.post.rawValue 
    request.setValue("bearer 5bac059b-eb2b-4e1b-914a-9de5b6a58577", forHTTPHeaderField: "Authorization") 
    request.setValue("application/json", forHTTPHeaderField: "Content-Type") 

    let data = try! JSONSerialization.data(withJSONObject: params as Any, options:JSONSerialization.WritingOptions.prettyPrinted) 

    let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue) 
    print(json!) 

    request.httpBody = json!.data(using: String.Encoding.utf8.rawValue) 

    Alamofire.request(request).responseJSON { response in 
     print(response.request ?? "no request") // original URL requ est 
     print(response.response ?? "no response") // HTTP URL response 
     print(response.data ?? "no data")  // server data 
     print(response.result) // result of response serialization 
     print(response.response?.statusCode ?? "noCode") 

     if(response.response?.statusCode != nil){ 
      switch response.response!.statusCode { 
      case 200: 
       print("Success") 
       let json = JSON(data: response.data!) 
       print(json) 
       sender.onSuccessCall() 
      case 400: 
       print("Error in authentication") 
      case 401: 
       print("Error authentication object was not found") 
      default: 
       print("dEfault") 
      } 
     } 
    } 
} 
1

請試試這個代碼

  let urlString = String(format : "Your URL") 


      let params: [String : Any] = [ 
       "profile": [ 
        "Type": [ 
        " Real Estate", 
        "Estater", 
        "Construction", 
        "Entertainment" 
        ], 
        "Size": [ 
        "large", 
        "small" 
        ], 
        "Level": [ 
        "A", 
        "B" 
        ], 
        "Name" : [ 
        "John", 
        "Harry" 
        ] 
       ] 
      ] 

      print(params) 

      let url = URL(string: urlString)! 



    let data = try! JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions.prettyPrinted) 

    let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue) 
    if let json = json { 
     print(json) 
    } 

    let jsonData = json!.data(using: String.Encoding.utf8.rawValue); 



      var request = URLRequest(url: url) 
    request.httpMethod = HTTPMethod.post.rawValue 
    request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type") 
    request.setValue("bearer e2ff3aa3-63a3-41d1-bc5a3e8c88adeaaa",forHTTPHeaderField: "Authorization") 
      request.httpBody = jsonData 

      Alamofire.request(request).responseJSON { 
       (response) in 

       switch response.result { 
       case .success(let JSON): 
        print("Success with JSON: \(JSON)") 



        break 

       case .failure(let error): 
        print("Request failed with error: \(error)") 
        //callback(response.result.value as? NSMutableDictionary,error as NSError?) 
        break 
       } 


       } 
       .responseString { response in 

        print("Response String: \(response.result.value)") 

      }