Pregunta

I'm calling a URL that either returns a file or a JSON with an error message. So, for example

resp = RestClient.get "my_url"
=> "\037\213\b\b\n\206XR\002\3....."

and

resp = RestClient.get "my_url"
=> "{\"status\": 1}"

I need to define if the output is a JSON or a file. So I could do something like this:

begin 
  JSON.parse(resp)
  # is a json
rescue ExceptionThatIDontRecallTheNameRightNow => e
  # it is a file
end

But this actually don't work because we would have a malformed json as a file.

So the question is, how can I verify if this answer is a file or a JSON?

¿Fue útil?

Solución

This seems to do it:

resp = RestClient.post(full_url, params, HTTP_HEADERS)
if resp.headers[:content_type] == 'application/octet-stream'
  resp
else
  resp = JSON.parse(resp)
  ...
end 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top