Concepts and principles
Characteristics
Supports synchronous blocking calls and asynchronous calls with callbacks.
Okhttp supports Android version 2.3 and above. For JDK, the minimum requirement is 1.7.
Request is a requested access in Okhttp, and builder is an auxiliary class. Response is the response in Okhttp.
Code section
Use Eventbus in your project:
S1. Adding a jar package or dependency
Compile ' com.squareup.okhttp3:okhttp:3.8.0 '
Compile ' com.squareup.okio:okio:1.13.0 '
S2. Create a Post/get request:
S3. Code obfuscation
-dontwarn okio.**
-dontwarn javax.annotation.Nullable
-dontwarn Javax.annotation.ParametersAreNonnullByDefault
OKHTTP Main methods:
Create request MediaType Media_type = Mediatype.parse ("Application/json; Charset=utf-8 "); Request Request = new Request.builder (). Post (Requestbody.create (Media_type, JSON)) . URL (URL). build ();//Create response response response = Client.newcall (Request). Execute (); Syncresponse response = Client.newcall (Request). Enqueue (New Callback () {//Async @Override public void OnFailure (call call, IOException e) {} @Override public void Onresponse (call call, Response Response) throws IOException {}});// Gets the result if (response.issuccessful ()) {Response.body (). String (); Timeout settings//Submit JSON Data sample public static void Postjsonexamasync () {String URL = "Http:localhost:8080/login/commituser Info "; String Postjson = "{}"; Requestbody BODY = requestbody.create (media_type, Postjson); Request Request = New Request.builder (). URL (URL). Post (body). Build (); Client.newcall (Request) Enqueue (new Callback () {@Override public void onfailure, ioexcept Ion e) {e.printstacktrace (); } @Override public void Onresponse (call call, Response Response) throws IOException { if (!response.issuccessful ()) throw new IOException ("Unexpected Code" + response); Headers responseheaders = Response.headers (); for (int i = 0; i < responseheaders.size (); i++) {System.out.println (Responseheaders.name (i) + ":" + Responseheaders.value (i)); } System.out.println (Response.body (). String ()); } }); }
Reference Documentation:
Github-okhttp Link2
GitHub Document-okio
Android okhttp Full parsing It's time to get to know okhttp.
Okhttp Using Tutorials
Android Okhttp Summary