Android Okhttp Request Package

Source: Internet
Author: User

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

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.