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 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 classUrlutil {Private StaticHttpClient HttpClient =NewHttpClient (); /*** @Title: Getdatafromurl * @Description: Get output results across domains based on URL, support HTTP *@paramstrurl * URL address to access *@paramparam * Parameters *@returnResult String *@throwsException*/       Public StaticString Getdatafromurl (String strurl, map<string, string> param)throwsException {URL url=NewURL (strURL); URLConnection Conn=url.openconnection (); Conn.setdooutput (true); OutputStreamWriter writer=NewOutputStreamWriter (Conn.getoutputstream ()); FinalStringBuilder SB =NewStringBuilder (Param.size () << 4);//4-Time Square        Finalset<string> keys =Param.keyset ();  for(FinalString Key:keys) {              FinalString value =Param.get (key); Sb.append (key); //cannot contain special charactersSb.append (' = '));              Sb.append (value); Sb.append (' & '); }          //remove the last ' & 'Sb.deletecharat (Sb.length ()-1);          Writer.write (Sb.tostring ());          Writer.flush ();            Writer.close (); InputStreamReader Reder=NewInputStreamReader (Conn.getinputstream (), "Utf-8"); BufferedReader Breader=NewBufferedReader (Reder); //BufferedWriter w = new BufferedWriter (New FileWriter ("D:/1.txt")); String content =NULL; String result=NULL;  while(content = Breader.readline ())! =NULL) {result+=content; }            returnresult; }        /*** @Title: Postmethod * @Description: Get output results across domains based on URL, support HTTPS *@paramURL * The URL address to access (http://www.xxx.com?) * @paramurlparm * Parameters (id=1212&pwd=2332) *@returnresult String*/       Public Staticstring postmethod (string url, string urlparm) {if(NULL= = URL | | "". Equals (URL)) {              //url = "http://www.baidu.com";             return NULL; } Postmethod Post=NewPostmethod (URL);//new Utf8postmethod (URL);         if(NULL! = Urlparm &&! "". Equals (Urlparm)) {string[] arr= Urlparm.split ("&"); namevaluepair[] Data=NewNamevaluepair[arr.length];  for(inti = 0; i < arr.length; i++) {String name= arr[i].substring (0, arr[i].lastindexof ("=")); String value= Arr[i].substring (Arr[i].lastindexof ("=") + 1); Data[i]=NewNamevaluepair (name, value);          } post.setrequestbody (data); }          intStatusCode = 0; String PageContent= ""; Try{StatusCode=Httpclient.executemethod (POST); if(StatusCode = = Httpstatus.sc_ok | | statusCode = =httpstatus.sc_moved_temporarily) {PageContent=post.getresponsebodyasstring (); returnPageContent; }          } Catch(Exception e) {e.printstacktrace (); return NULL; } finally{post.releaseconnection (); }          return NULL; }         Public StaticString doPost (string URL, string json)throwsException {postmethod Postmethod=Newpostmethod (URL); Stringrequestentity requestentity=NewStringrequestentity (JSON, "Application/json", "UTF-8");          Postmethod.setrequestentity (requestentity); /*send the request and get the response object*/          intStatusCode =Httpclient.executemethod (Postmethod); String result=NULL; if(StatusCode = =HTTPSTATUS.SC_OK) {Result=postmethod.getresponsebodyasstring (); } Else{System.out.println ("Method failed:" +postmethod.getstatusline ()); }          returnresult; }         Public StaticString post (string URL, map<string, string>params) {defaulthttpclient httpclient=Newdefaulthttpclient (); String Body=NULL; HttpPost Post=postform (URL, params); Body=Invoke (httpclient, post);          Httpclient.getconnectionmanager (). Shutdown (); returnbody; }        Private StaticHttpPost postform (String URL, map<string, string>params) {HttpPost Httpost=Newhttppost (URL); List<BasicNameValuePair> Nvps =NewArraylist<basicnamevaluepair>(); Set<String> KeySet =Params.keyset ();  for(String key:keyset) {Basicnamevaluepair Basicnamevaluepair=NewBasicnamevaluepair (Key, Params.get (key));          Nvps.add (Basicnamevaluepair); }          Try{httpost.setentity (Newurlencodedformentity (Nvps, HTTP.          Utf_8)); } Catch(unsupportedencodingexception e) {e.printstacktrace (); }          returnHttpost; }        Private StaticString Invoke (defaulthttpclient httpclient, Httpurirequest httpost) {HttpResponse response=SendRequest (httpclient, httpost); String Body=Paseresponse (response); returnbody; }        Private StaticHttpResponse SendRequest (defaulthttpclient httpclient, Httpurirequest httpost) {HttpResponse response=NULL; Try{Response=Httpclient.execute (httpost); } Catch(Exception e) {e.printstacktrace (); }          returnresponse; }        Private StaticString Paseresponse (httpresponse response) {httpentity entity=response.getentity (); String Body=NULL; Try{Body=entityutils.tostring (entity); } Catch(Exception e) {e.printstacktrace (); }          returnbody; }         Public Static voidMain (string[] args)throwsException {String URL= "Http://ip:8082/security/auth/outside.do"; Map<string, string> map =NewHashmap<string, string>(); Map.put ("LoginName", "root"); Map.put ("Code", "vms2.0"); String msg=post (URL, map); Jsonarray Jary=Jsonutil.json2jsonarray (msg);  for(inti = 0; I < jary.length (); i++) {Jsonobject obj=Jary.getjsonobject (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);     }  }


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.

Cross-domain Problem resolution (httpclient Security cross-domain & 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.