In order for people to be able to help you better, can you also do a $res->as_string and post the result. The response may contain additional information to understand the reason why the server is returning the 401 Unauthorized.
I'm also not a professional on these matters, but I think that the 401 can also mean that the server wants additional authentication. (Meaning your request is challenged). I tried to find information about this and eventually I found this doc which may be useful to you: https://www.ietf.org/rfc/rfc2617.txt