简体   繁体   中英

Alamofire post request with params in the URL in swift

I have a post method with base url and various parameters appended in the base url itself. The code is given below:

 let todosEndpoint:String =  "https://xxxxxxx/api/post_schedule_form_data?service_type=nanny&start_date=07/20/2020&start_time=06:00&end_date=07/20/2020&end_time=09:00&work_description=Work Description&special_instructions=Special Instructions&location_address=location_address&postal_code=abc123&current_profile_id=10"

 let header: HTTPHeaders = ["Content-Type":"application/json","x-token":self.usertoken!]
           
           print("the url is",todosEndpoint)

        AF.request(todosEndpoint, method: .post, encoding: JSONEncoding.default, headers: header)
               .responseJSON { response in
                switch response.result {
                               case .success(let json):
                                   print("Validation Successful",json)
                    case let .failure(error):
                                       print(error)
                                   }
                    }

I do not get any response in the code.What could the error be?

Looks to me like you've got a number of illegal characters in your query params (eg ":", "/", " ").

I suggest you build your URL using URLComponents. Pass in the endpoint and the query params and then get back the path. That will show you what needs to be escaped.

Edit:

I guess I was wrong about ":" and "/". It looks like those are legal as part of a query param value.

This code:

var components = URLComponents()
components.scheme = "https"
components.host = "xxxxxxx"
components.path = "/api/post_schedule_form_data"
components.queryItems = [
    URLQueryItem(name: "service_type", value: "nanny"),
    URLQueryItem(name: "start_date", value: "07/20/2020"),
    URLQueryItem(name: "start_time", value: "06:00"),
    URLQueryItem(name: "end_date", value: "07/20/2020"),
    URLQueryItem(name: "end_time", value: "09:00"),
    URLQueryItem(name: "work_description", value: "Work Description"),
    URLQueryItem(name: "special_instructions", value: "Special Instructions"),
    URLQueryItem(name: "location_address", value: "location_address"),
    URLQueryItem(name: "postal_code", value: "abc123"),
    URLQueryItem(name: "current_profile_id", value: "10"),
]

print(components.string ?? "nil")

Outputs the string

https://xxxxxxx/api/post_schedule_form_data?service_type=nanny&start_date=07/20/2020&start_time=06:00&end_date=07/20/2020&end_time=09:00&work_description=Work%20Description&special_instructions=Special%20Instructions&location_address=location_address&postal_code=abc123&current_profile_id=10

Note that the spaces get escaped as %20 .

That is probably the only illegal part of your URL string.

URLComponents is your friend because it applies escaping to the different parts of the URL as needed, and enforces the correct escaping rules for each of the different parts of the URL.

Edit #2:

This code:

let urlString: String =  "https://xxxxxxx/api/post_schedule_form_data?service_type=nanny&start_date=07/20/2020&start_time=06:00&end_date=07/20/2020&end_time=09:00&work_description=Work Description&special_instructions=Special Instructions&location_address=location_address&postal_code=abc123&current_profile_id=10"

let componentsFromString = URLComponents(string: urlString)

print(componentsFromString?.string ?? "nil" )

displays "nil"

That tells you there is something illegal about your URL string.

Your headers are not going through correctly... Also, you're passing " " (spaces) in your URL, just replace them with "%20". The correct way to do this would be:

let url:String =  "https://xxxxxxx/api/post_schedule_form_data?service_type=nanny&start_date=07/20/2020&start_time=06:00&end_date=07/20/2020&end_time=09:00&work_description=Work Description&special_instructions=Special Instructions&location_address=location_address&postal_code=abc123&current_profile_id=10".replacingOccurrences(of: " ", with: "%20")

var request = URLRequest(url:  NSURL(string: url)! as URL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(self.usertoken!, forHTTPHeaderField: "x-token")
AF.request(request).responseJSON { response in
     switch response.result {
            case .success(let json):
                 print("Validation Successful",json)
            case let .failure(error):
                  print(error)
      }
}

You are force unwrapping self.usertoken, so beware of that as well! Also seems like the date in the URL has "/" which you must change to "%2F" in the URL or better the format in the backend!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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