RxAlamofire make post call with json body

2.2k views Asked by At

I want to make post call using RxAlamofire not able to find any method to do so

tried using requestJSON method but there is no paramter to pass post json in

 RxAlamofire.requestJSON(.post, url)

how to make post call and pass json data to post call in RxAlamofire

4

There are 4 answers

0
amodkanthe On BEST ANSWER

Use following code

  var request = URLRequest(url: URL(string: "https://some_url")!)
    //Following code to pass post json 
    request.httpBody = json
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    RxAlamofire.request(request as URLRequestConvertible).responseJSON().asObservable()
2
mkowal87 On

use this function with proper parameters ancoding

public func urlRequest(_ method: Alamofire.HTTPMethod,
                   _ url: URLConvertible,
                   parameters: [String: Any]? = nil,
                   encoding: ParameterEncoding = URLEncoding.default,
                   headers: [String: String]? = nil)
0
Versus On

Using jsonEncoding

RxAlamofire.requestJSON(.post, url, encode: JsonEncoding.default)

It works for me~

0
Songzhw On

amodkanthe's solution works. But its return value is not friendly. So I changed it a litte bit

    var request = URLRequest(url: URL(string: "https://some_url")!)
    request.httpBody = jsonData  // jsonData is a Data type
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type") // this line is important
    RxAlamofire.requestJSON() //=> returns a Observable<(HttpURLResponse, Any)>, the `Any` type is actually a dictionary

p.s. the version I'm using is RxAlamofire(6.1.1)