Cross-domain Problem resolution (httpclient security cross-domain & JSONP cross-domain)

Source: Internet
Author: User

1 Error Scenarios

Today to deploy the project to the external network, there is this problem, I put two projects into their native tomcat, code debugging, execution

There is no problem, once I need to invoke the interface of the project B on the other server, will be error, can not be called through Ajax SPRINGMVC interface,

What is the reason for this?

error on Web side when I use JSON Ajax POST request to pass data:XMLHttpRequest cannot loadhttp://ip:8082/security/auth/outside.do. Origin http://ip:8080 is isn't allowed by Access-control-allow-origin.

2 Initial knowledge of Jsonp                                

After searching the internet, most of the internet is a cross-domain problem. Resolving cross-domain issues It is said that Jsonp, Baidu has an article, whether 3,721 or so

Sub-Ajax passed the data type datatype changed to JSONP, and use Get method, pure feel, JSON and JSONP no difference, execution, error, such as

What you see:

None of the above is allowed .... Mistake, turned out to be just 500 of the error, that Jsonp played some role, my bug is the "cross-domain" on the internet.

And what exactly is a cross-domain?

3 What is a cross-domain? What is non-cross-domain?

There is not too much to test, a word: The same IP, the same network protocol, the same port. All three are satisfied is the same domain, otherwise it is

Cross-domain issue.

And why didn't the developer initially set it all to be cross-domain? Why is the default not cross-domain? This involves the homologous policy

Slightly, for the security of the system, a famous security strategy was proposed by Netscape.

This strategy is used by all JavaScript-enabled browsers today.

The so-called homology is the domain name. protocol, Port same. When we open in the browser Baidu and Google two sites, Baidu browser in the run a script

Check which page this script belongs to. That is to check whether the same origin, only and Baidu homologous script will be run, assuming there is no homologous strategy, that

Casually to Baidu into a JS script, play a malicious ads, through JS steal information. It's very unsafe.

4 How to solve the cross-domain problem? Why can jsonp solve cross-domain problems? What is the difference from JSON?

There are several ways to resolve cross-domain issues, such as the following.

4.1 Programme I

The AJAX request address changes to its own system's back-end address, then requests the URL in its own background with httpclient. Encapsulated cross-domain request URL Tool class

The code is seen in the following example.

<span style= "FONT-SIZE:18PX;" > @SuppressWarnings ("All") public final class Urlutil {private static HttpClient HttpClient = new HttpClient ();/** * @Tit Le:getdatafromurl * @Description: Gets the output from a cross-domain URL. Support HTTP * @param strurl * URL address to access * @param param * References * @return result string * @throws Exception */public static string Getdatafromurl (string strurl, map<string, string> param) throws Exception {URL url = new URL (strurl); Rlconnection conn = Url.openconnection (); Conn.setdooutput (true); OutputStreamWriter writer = new OutputStreamWriter ( Conn.getoutputstream ()); final StringBuilder sb = new StringBuilder (Param.size () << 4); 4-time final set<string> keys = Param.keyset (); for (final string Key:keys) {final String value = Param.get (key); sb. Append (key); Cannot include special characters sb.append (' = '); Sb.append (value); Sb.append (' & ');} Remove the last ' & ' from Sb.deletecharat (Sb.length ()-1), Writer.write (Sb.tostring ()); Writer.flush (); Writer.close (); I Nputstreamreader Reder = new InputstrEamreader (Conn.getinputstream (), "utf-8"); BufferedReader breader = new BufferedReader (reder);//BufferedWriter w = new BufferedWriter (New FileWriter ("D:/1.txt")); String content = null; String result = null;while (content = Breader.readline ()) = null) {result + = content;} return result;} /** * @Title: Postmethod * @Description: Get output results across domains by URL. Support HTTPS * @param URL * The URL address to access (http://www.xxx.com?) * @param urlparm * (id=1212&pwd=2332) * @return result string */public static string Postmethod (string url, string urlparm) {if (null = = URL | | "". Equals (URL)) {//url = "http://www.baidu.com"; return null;} Postmethod post = new Postmethod (URL); New Utf8postmethod (URL); if (null! = Urlparm &&! "). Equals (Urlparm)) {string[] arr = Urlparm.split ("&"); namevaluepair[] data = new Namevaluepair[arr.length];for (int i = 0; i < arr.length; i++) {String name = Arr[i].substri Ng (0, arr[i].lastindexof ("=")); String value = arr[i].substring (Arr[i].lastindexof ("=") + 1);d Ata[i] = new Namevaluepair (name, value);} Post.setrequestbody (data);} int statusCode = 0; String pagecontent = ""; try {statusCode = Httpclient.executemethod (post); if (StatusCode = = HTTPSTATUS.SC_OK | | StatusCode = = httpstatus.sc_moved_temporarily) {pagecontent = Post.getresponsebodyasstring (); return pagecontent;}} catch (Exception e) {e.printstacktrace (); return null;} finally {post.releaseconnection ();} return null;} public static string DoPost (string URL, string json) throws Exception {Postmethod Postmethod = new Postmethod (URL); Stringrequestentity requestentity = new Stringrequestentity (JSON, "Application/json", "UTF-8"); Postmethod.setrequestentity (requestentity);/* Send the request and get the response object */int StatusCode = Httpclient.executemethod (Postmethod); String result = null;if (StatusCode = = HTTPSTATUS.SC_OK) {result = Postmethod.getresponsebodyasstring ();} else {System.ou T.println ("Method failed:" + postmethod.getstatusline ());} return result;} public static string post (string URL, map<string, string> params) {Defaulthttpclient httpclient = new Defaulthttpclient (); String BODY = null; HttpPost post = postform (URL, params); body = Invoke (httpclient, post); Httpclient.getconnectionmanager (). Shutdown (); return body;} private static HttpPost postform (String URL, map<string, string> params) {HttpPost httpost = new HttpPost (URL); list<basicnamevaluepair> Nvps = new arraylist<basicnamevaluepair> (); set<string> KeySet = Params.keyset (); for (String key:keyset) {Basicnamevaluepair Basicnamevaluepair = new BasicNam Evaluepair (Key, Params.get (key)); Nvps.add (Basicnamevaluepair);} try {httpost.setentity (new urlencodedformentity (Nvps, HTTP). utf_8));} catch (Unsupportedencodingexception e) {e.printstacktrace ();} return httpost;} private static String Invoke (Defaulthttpclient httpclient, Httpurirequest httpost) {HttpResponse response = SendRequest ( HttpClient, Httpost); String BODY = paseresponse (response); return body;} private static HttpResponse SendRequest (Defaulthttpclient httpclient, HttpurIrequest httpost) {HttpResponse response = null;try {response = Httpclient.execute (httpost);} catch (Exception e) {E.print StackTrace ();} return response;} private static String Paseresponse (HttpResponse response) {httpentity entity = response.getentity (); String BODY = null;try {BODY = entityutils.tostring (entity),} catch (Exception e) {e.printstacktrace ();} return body;} public static void Main (string[] args) throws Exception {String url = "Http://ip:8082/security/auth/outside.do"; map<string, string> map = new hashmap<string, string> (), Map.put ("LoginName", "root"), Map.put ("Code", " Vms2.0 "); String msg = post (URL, map); Jsonarray jary = Jsonutil.json2jsonarray (msg); for (int i = 0; i < jary.length (); i++) {Jsonobject obj = jary.getjsonobj ECT (i); System.out.println (obj),//system.out.print (obj.getstring ("ClassID")),//system.out.print ("\ T" +obj.getstring (" ClassName "));//system.out.println (" \ T "+obj.getstring (" Sonclass "));} System.out.println (Jary);}} </span>


Of course to import the Httpclient-4.3.1.jar package into your own project OH. This puts the requested number of parameters into the map. Cross-domain requests are implemented through Httpclent.

4.2 Solution Two

The data transfer between the two systems is done through the Ajax POST request, which is the way to pass the JSON, where we can use the JSONP. But

JSON is very different from JSONP. First of all, the god horse is the JSON, say God horse is jsonp.

Json

Full-spelling (JavaScript Object Notation) Lightweight data Interchange format for easy machine parsing and generation. Based on JavaScript

A subset of programming LANGUAGE,STANDARDECMA Edition December1999. JSON completely language-independent text grid

, but it also uses a habit similar to the C language family (include C C + + C # java javaScript perl python). These features make the JSON

Become the ideal data exchange language. Format is Key,value format, detailed will not repeat.

Jsonp

JSONP full spell Yes (JSON with Padding) is a usage pattern of JSON, Padding meaning filler, padding, filling, filling. JSON can

To say is a noun, and jsonp is a verb-bin phrase, the two have a connection, but there are essential differences, like rice and rice filled into the bowl, the rice and

Rice filling is the same, we naturally understand.

Jsonp is a kind of cross-domain, how to solve the cross-domain problem through Jsonp detailed? This article is too long, we are in the next chapter. Goodnight...

Cross-domain Problem resolution (httpclient security cross-domain &amp; JSONP cross-domain)

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.