简体   繁体   English

如何在Alamofire中使用正文和标头请求JSON?

[英]How to request JSON with body and header in Alamofire?

I had tried with the following code for the request but result with 400 error. 我曾尝试使用以下代码进行请求,但结果为400错误。 API consists of header and body. API由标头和正文组成。 Header had two fields that are "Authorization" and "Content-Type". 标头有两个字段,分别是“授权”和“内容类型”。 Body format is added to params below. 正文格式已添加到下面的参数中。

在此处输入图片说明

在此处输入图片说明

    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")
                }
            }
        }
    }

Please help to slove on this problem. 请帮助解决这个问题。

I solved the problem, The correct way added below. 我解决了问题,下面添加了正确的方法。

   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")
            }
        }
    }
}

Please Try this code 请尝试此代码

            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)")

            }

Sometime we need URLEncoding.httpBody type for post method hope it may help you and 有时我们需要URLEncoding.httpBody类型作为post方法,希望对您有所帮助,并且

 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!!")
                }

            }

Use URLConvertible type url in baseUrl baseUrl中使用URLConvertible类型的url

Solution is below: 解决方案如下:

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")
                }
            }
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM