开发者

Implementing an HTTP proxy to overcome cross-site AJAX requests restrictions (?)

I have a Spring-MVC webapp (3.0.5-RELEASE) which needs to access JSON webservices from another webapp on a different sub-domain (from the client/browser via AJAX).

I've solved this in the past by either:

  1. writing a simple controller that proxies the requests, using Apache Commons HttpClient to handle the requests. Thus overcoming the cross-site/cross-origin request security limitations of most browsers

  2. implementing a JSONP service on the server side (when calling our own JSON services) - not always possible

In the case wher开发者_JAVA技巧e JSONP is not possible, is there a better way of doing (1.)?

and/or

Is there a library that will handle this for me? So I don't have to write all the HttpClient code myself - its not a lot of code, but I wonder if I'm (badly) re-inventing the wheel.


I have often had to consume third party web services (API), and as you mentioned, JSONP is not always an option. This is how I go about designing:

  1. If the API is user centric, it has to provide a jsonp interface and that's what I will use. User centric means that you cannot perceive any reason to call the API, do some computations with the response, may be call one of your ajax services and then combine the response and show the user.

  2. If my use case includes calling the API, and then acting on the response, like calling additional services from my application, combining the data and then showing it to the user, I would prefer not doing this in the browser. I would instead use RestTemplate and make backend api calls to the service. In which case there are no cross domain restrictions.

The only case where using a Server Proxy to bypass jsonp is when you are creating a Product that allows people to build custom plugins, plugins which are hosted on your page, but need to make Ajax calls to the app developers servers. This is a very involved case! (As as example look at how Apigee creates Public Facing REST API around your existing urls, or how Zendesk allows you to develop apps)

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜