At present, the network tools used in the development of Android are okhttp, but the use of okhttp is not very convenient, and it is very convenient for the network call to encapsulate the request on the basis of okhttp.
Directly below the code.
Request Encapsulation
Public classHttputil { Public Static voidSendokhttprequest (String address, map<string,string> head,map<string,string>BODY,OKHTTP3. Callback Callback) {okhttpclient client=Newokhttpclient (); Request.builder Builder=Newrequest.builder (). URL (address); if(head!=NULL&&head.size () >0){ for(Map.entry<string, string>Entry:head.entrySet ()) {Builder.addheader (Entry.getkey (), Entry.getvalue ()); }} formbody.builder Formbody=NewFormbody.builder (); if(body!=NULL&&body.size () >0){ for(Map.entry<string, string>Entry:head.entrySet ()) {Formbody.add (Entry.getkey (), Entry.getvalue ()); }} requestbody Requestbody=Formbody.build (); Request Request=builder.post (requestbody). build (); Client.newcall (Request). Enqueue (callback); }}
The above is a simple encapsulation of the put request of okhttp, four parameters are
1. Request Address
2. Request header, in the form of a map, if you do not need to pass in null
3. Carry parameters, also in the form of a map, such as no parameter passed to null
4. Callback function
Called in code
Map<string,string> body=new hashmap<string, string> (); Body.put ("UserName", loginName); Body.put ("password", password);
Httputil.sendokhttprequest (getString (R.STRING.IP) + "/xxx/login", Null,body,new Callback () { @ Override publicvoid onfailure (called call, IOException e) { //request failed } @Override Public void throws IOException { final string responsetext=response.body (). String (); Request succeeded } );
Note that the callback is okhttp and should be noticed when introduced.
Android okhttp Request encapsulation