1 Error Scenarios
Today to deploy the project to the external network, there are such problems, I put two projects into their native tomcat, code debugging, running
There is no problem, once I need to call the interface to 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, regardless of 3,721 on the
Sub-Ajax passed the data type datatype changed to JSONP, and use get way, simply think, JSON and JSONP no difference, run, error, such as
As shown:
None of the above is allowed .... Error, turned out to be only 500 errors, indicating 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?
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 is
Cross-domain issue. And why didn't the developer initially make it all 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 policy is now used by all JavaScript-enabled browsers.
The so-called homology is, domain name, protocol, port the same. When we open in the browser Baidu and Google two sites, Baidu browser in the execution of a script
Time will check which page this script belongs to, that is, check whether the same origin, only and Baidu homologous script will be executed, if there is no homologous strategy, that
Casually to Baidu into a JS script, play a malicious ads, through JS steal information, this is very unsafe.
4 How are cross-domain issues resolved? Why can jsonp solve cross-domain problems? What is the difference from JSON?
There are several solutions to solve cross-domain issues, as follows.
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 shown below.
<span style= "FONT-SIZE:18PX;" > @SuppressWarnings ("All") public final class Urlutil {private static HttpClient HttpClient = new HttpClient ();/** * @Tit Le:getdatafromurl * @Description: Get output results across domains based on URL, support HTTP * @param strurl * URL address to access * @param param * Parameter * @return Result string * @throws Exception */public static string Getdatafromurl (string strurl, map<string, string> par AM) throws Exception {URL url = new URL (strurl); URLConnection 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 contain 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 based on URL, support HTTPS * @param URL * URL to access (http://www.xxx.com?) * @param urlparm * PARAMETER (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 parameter contents into the map and implements cross-domain requests through httpclent.
4.2 Solution II
The data transfer between the two systems is done through Ajax post requests, which are passed through JSON, where we can use the Jsonp method, 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
Similar to the C-language family (include C C + + C # java javaScript perl python), which makes the JSON
Become the ideal data exchange language. Format is key,value format, specifically do not repeat it.
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, the two are linked, 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 the cross-domain of the loopholes, in the end through JSONP how to solve the cross-domain problem? This article is too long, we are in the next chapter. Goodnight...
Cross-domain Problem resolution (httpclient Security cross-domain & JSONP cross-domain)