Purpose: One code runs three places, iOS, Android, Web. The bottom of the communication is also shared. The HTTP request used by React-web is JSONP, and his feature is that only get requests can be sent, and the server will be brought back with the callback field that requested it.
Client implementation Scenarios:
Place POST request content base64 in URL
var fetch = Platform.os = = ' web '?
Require (' REACTJSONP '): Require (' reactfetch '); Post (URL, body) { Let FetchOptions = { method: ' Post ', &N Bsp Deadline:kdeadline, Timeout:kdeadline, headers: {
' Accept ': ' Application/json ', , ' content-type ': ' Application/json ', ' uutype ': Appglobal.uutype, ' latitude ': appglobal.l Atitude, ' longitude ': appglobal.longitude, ' token ':
Appglobal.usertoken, }, body:JSON.stringify (body) }
Console.log (' request header is = = ' +json.stringify (fetchoptions)); if (Platform.os = = ' web ') { //Check if the user set their own params, and IF not add a? To start a list of params URL = url.indexof ('? ') = =-1?
'? ': ' & ';
//placing parameters inside the URL var optstring = json.stringify (fetchoptions);
var options = new Buffer (optstring). toString ("base64");
URL = ' options= ' +options; } return fetch (URL, fetchoptions) then (res=>{ &NBSP ; try { Console.log (' Post Method res = ' + JSON
. Stringify (res));
return Res.json (); } catch (e) { return parseerror
; &NBSP, &NBS P (res) => { Console.log (' request REJECTed ${res} ');
throw res;
}) }
Service-side scenario:
1. Support JSONP
public static void Renderjsonporjson (HttpServletResponse response,final String callbackname, Final object, final S Tring. Headers) {
if (callbackname!=null&&!callbackname.equals ("")) {
Renderjsonp (response, Callbackname, object, headers);
else {
Renderjson (response, object, headers);
}
}
2. Support the decoding of post content to the URL
The process is: Modify the Dispatchcontroller for customization, then rewrite the httpservletrequest within the custom class, decode the post content in the URL, and fill in the contents of the new request's head and body.
public class Customdispatch extends Dispatcherservlet {
@Autowired
protected void Dodispatch ( HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out.println (" Customdispatch---------Dodispatch ");
String option = Request.getparameter ("Options");
if (option!= null) {//
JSONP Requests Special handling, modify the contents of the request (because JSONP can only get requests)
// System.out.println (" Customdispatch---------dodispatch Options ");
HashMap m=new HashMap (Request.getparametermap ());
Remove the parameter base64 decode
byte[] b = encodes.decodebase64 (option);
String jsonoption = new string (b);
Replace request
HttpServletRequest req = (httpservletrequest) request;
Httprequestchangeable wraprequest=new httprequestchangeable (req,m,jsonoption);
Request=wraprequest; This is rquest just like the request of itself
}else{
}
super.dodispatch (request, response);
}
Package com.defa.tcm.common.customDispatch;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.nio.charset.Charset;
Import Javax.servlet.ServletRequest; public class Httphelper {/** * Fetch request BODY * * @param requests * @return/Public
Static String getbodystring (ServletRequest request) {StringBuilder SB = new StringBuilder ();
InputStream inputstream = null;
BufferedReader reader = null;
try {InputStream = Request.getinputstream ();
reader = new BufferedReader (new InputStreamReader (InputStream, Charset.forname ("UTF-8"));
String line = "";
while (line = Reader.readline ())!= null) {sb.append (line);
} catch (IOException e) {e.printstacktrace (); finally {if (InputstreaM!= null) {try {inputstream.close ();
catch (IOException e) {e.printstacktrace ();
} if (reader!= null) {try {reader.close ();
catch (IOException e) {e.printstacktrace ();
}} return sb.tostring ();
}
}
@SuppressWarnings ("Unchecked") public class Httprequestchangeable extends Httpservletrequestwrapper {private Map P
Arams;
Private final byte[] body;
Private final HashMap Headershash;
Private final List Headkey;
Public httprequestchangeable (HttpServletRequest request, Map newparams,string postcontent) {super (request);
This.params = Newparams;
Jsonobject jsonobj = Jsonobject.fromobject (postcontent);
String bodystr = jsonobj.getstring ("Body");
String headers = jsonobj.getstring ("headers");
Jsonobject Jsonhead = jsonobject.fromobject (headers);
Headershash = new HashMap ();
Parsertomap (Headers,headershash);
Print head//Enumeration E = Request.getheadernames ();
while (E.hasmoreelements ()) {//String name = (String) e.nextelement ();
String value = Request.getheader (name);
System.out.println (name+ "=" +value);//Set Head key Headkey = new ArrayList ();
Iterator Keys=jsonhead.keys ();
while (Keys.hasnext ()) {string key= (String) keys.next ();
if (Key!= "Body") {Headkey.add (key);
}//Set head and BODY = Bodystr.getbytes (Charset.forname ("UTF-8"));
BODY = httphelper.getbodystring (Request). GetBytes (Charset.forname ("UTF-8"));
Public Map Getparametermap () {return params;
Public enumeration Getparameternames () {vector L = new vector (Params.keyset ());
return l.elements ();
Public string[] Getparametervalues (String name) {Object v = params.get (name);
if (v = = null) {return null;
else if (v instanceof string[]) {return (string[]) v; else if (v instanceof String) {returnNew string[] {(String) v};
else {return new string[] {v.tostring ()};
} public string GetParameter (string name) {Object v = params.get (name);
if (v = = null) {return null;
else if (v instanceof string[]) {string[] Strarr = (string[)) v;
if (Strarr.length > 0) {return strarr[0];
else {return null;
Or else if (v instanceof string) {return (string) v;
else {return v.tostring (); } @Override Public BufferedReader Getreader () throws IOException {return new BUFFEREDR
Eader (New InputStreamReader (getInputStream ())); @Override public ServletInputStream getInputStream () throws IOException {final BYTEARRAYINP
Utstream Bais = new Bytearrayinputstream (body); return new ServletInputStream () {@Override public int read () throws IOException {
return Bais.read ();
@Override public boolean isfinished () {if (bais.available () = 0) {return true;
return false;
@Override public boolean IsReady () {if (bais.available () > 0) {return true;
return false;
@Override public void Setreadlistener (Readlistener readlistener) {//TODO auto-generated stub
}
}; @Override Public String GetHeader (string name) {return (string) headershash.get (name);/RE
Turn super.getheader (name); @Override public enumeration<string> Getheadernames () {return new enumeration () {int Co
UNT = Headkey.size ();
int curindex = 0;
@Override public boolean hasmoreelements () {if (Curindex < count) {return true; RetUrn false;
@Override public Object nextelement () {if (Curindex < count) {Object res = headkey.get (curindex++);
return res;
return null;
}
};
return Super.getheadernames (); @Override Public enumeration<string> getheaders (final String name) {return new enumeration (
) {int count = 1;
int curindex = 0;
@Override public boolean hasmoreelements () {if (Curindex < count) {return true;
return false;
@Override public Object nextelement () {if (Curindex < count) {curindex++;
return Headershash.get (name);
return null;
}
};
return super.getheaders (name);
}//public static Map Parsertomap (String s,map initmap) {Map map= initmap;
if (map = = null) {map = new HashMap ();
} jsonobject Json=jsonobject.fromobject (s); Iterator Keys=json.keys ();
while (Keys.hasnext ()) {string key= (String) keys.next ();
String Value=json.get (key). ToString ();
if (Value.startswith ("{") &&value.endswith ("}")) {Map.put (Key, Parsertomap (Value,null));
}else{map.put (key, value);
} return map; public static final byte[] Readbytes (InputStream is, int contentlen) {if (Contentlen > 0) {int Readlen =
0;
int readlengththistime = 0;
byte[] message = new Byte[contentlen];
try {while (Readlen!= contentlen) {readlengththistime = is.read (message, Readlen, Contentlen-readlen);
if (readlengththistime = = 1) {//Should not happen.
Break
} Readlen + = Readlengththistime;
} return message;
catch (IOException e) {//Ignore//E.printstacktrace ();
} return new byte[] {}; }
}