简体   繁体   中英

Accessing the filename in an HTTParty response?

I am trying to parse the response from an api that has content type text/csv in a Ruby application. I am making the request using the HTTParty library. I know the filename is typically stored in the response headers under Content-Disposition, but HTTParty does not seem to be correctly parsing this particular header.

My best attempt at a fix looks like:

csv_response = HTTParty.get('service.com/csv')
content_disposition = CGI::parse(catalog_response.headers['Content-Disposition'])

This is where I'm stuck because CGI parse is returning a hash with the filename object containing a leading space and escaped quotes surrounding the filename like:

{' filename' => '\"file.csv\"'}

Am I parsing the response correctly? Is there a more reasonable way to access the filename using HTTParty?

You don't want the filename. You can use CSV.parse instead.

csv_response = HTTParty.get('service.com/csv')
CSV.parse(csv_response.body, headers: true) do |row|
  # do something
end

Remove the headers: true if your CSV doesn't have a header row.

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