Use httpclient to replace JSONP cross-domain solution for clients

Source: Internet
Author: User

Recently took over a project, the new project needs to call the interface of the old project, but the old project and the new project is no longer the same domain name, so the cross-domain calls must be made, but the old project can not make any changes, so JSONP can not be solved, so think of the use of httpclient to serve the "cross-domain "To replace the JSONP client cross-domain scenario.

In the last blog post, the cross-domain principle of JSONP is analyzed in detail, and this paper uses httpclient to replace JSONP client cross-domain scheme.

First go to http://hc.apache.org/downloads.cgi download the latest version of HttpClient. Unzip the tutorial folder with an Introduction to HTML and PDF usage.

The following implements Jsonservlet in a HTML5 project that accesses 8080 ports across domains from the 8888 Port HTML4 project:

1) Create an intermediary agent Servelt and a tool class in HTML4, with the following code:

Import Java.io.ioexception;import Java.io.outputstream;import Org.apache.http.httpentity;import Org.apache.http.client.methods.closeablehttpresponse;import Org.apache.http.client.methods.httppost;import Org.apache.http.impl.client.closeablehttpclient;import Org.apache.http.impl.client.httpclients;public Class Httputil{public Static Boolean returnresponseofurl (String URL, outputstream os) {closeablehttpclient httpclient = Httpclients.createdefault (); HttpPost HttpPost = new HttpPost (URL); Closeablehttpresponse response = Null;try{response = Httpclient.execute (HttpPost); httpentity entity = response.getentity (); Entity.writeto (OS); return true;} catch (IOException e) {e.printstacktrace (); return false;} Finally{if (response! = null) {Try{response.close ();} catch (IOException e) {e.printstacktrace ();}}}}

The intermediate proxy servlet code is as follows:

@WebServlet ("/httpclientservlet") public class Httpclientservlet extends HttpServlet {private static final long Serialversionuid = 1L;           Public Httpclientservlet ()     {        super ();    } protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { This.dopost (request, response);} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { String url = request.getparameter ("url"); if (URL! = null) {if (! Httputil.returnresponseofurl (URL, Response.getoutputstream ())) {if (! Httputil.returnresponseofurl (URL, Response.getoutputstream ())) {//If an error occurs, try again//log.error ("url:" + URL);}}}

The code for the access page in the HTML4 project is as follows:

<!doctype html>

above pass: Url=http://localhost:8080/html5/jsonservlet The URL address that we eventually want to cross-domain access to httpclientservlet under our own server. And then in Httpclientservlet uses httpclient to access the servlet in the cross-domain URL, and after success returns the returned results to the client .

The servlet code for cross-domain access in the HTML5 project is as follows:

@WebServlet ("/jsonservlet") Public classJsonservletextendsHttpServlet {Private Static Final LongSerialversionuid = 4335775212856826743L; protected voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, ioexception {User User=NewUser (); User.setname ("Yuanfang"); User.setage (100); Object obj=Json.tojson (user);            SYSTEM.OUT.PRINTLN (user); //[email protected]System.out.println (obj);//{"Age": +, "name": "Yuanfang"}Response.getwriter (). println (obj); }    protected voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException { This. DoPost (request, response); }}

Starting with 8888 and 8080 ports of Tomcat, accessing http://localhost:8888/html4/jsonp.html, the results are as follows:

We notice that the second and third items are printed in undefined, because the intermediate proxy's Httpclientservlet uses the direct output stream, so the result of the final return is not the JSON object, but the string, so we need to use var user = Json.parse (data); To parse it into JavaScript objects, so the fourth and fifth items are normally output.

Easy, ^__^.

Use httpclient to replace JSONP cross-domain solution for clients

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.