The reason it works with Java is that Java is not run in the client's browser. For security reasons, browsers will not allow Javascript AJAX requests to domains other than the domain the page was loaded from. For example, if you load a page from http://www.example.com/
, the javascript from that page will not be able to do AJAX requests to http://api.othersite.com/
or even http://api.example.com/
.
There are some workarounds. One is JSONP (http://en.wikipedia.org/wiki/JSONP) and another is to set the CORS headers (http://en.wikipedia.org/wiki/Cross-origin_resource_sharing). Both requires changes to the API you are calling, so you can't solve it on your side only.
What you could do is add a resource on your server, such as http://www.example.com/api/resource
which then, in your backend (Java in your case?), makes a request to http://api.othersite.com/
using code similar to what you wrote in the question. Your Javascript could then call http://www.example.com/api/resource
without problems. In short, you are proxying the requests through your backend to the third-party API.