Related articles
Android Network Programming (i) HTTP protocol principle
Android Network Programming (ii) HttpClient and HttpURLConnection
Android Network Programming (iii) Volley usage full analysis
Android Network Programming (iv) parsing from source code volley
Android Network Programming (v) okhttp2.x usage full analysis
Preface
The previous article introduced the use of okhttp2.x, this article we have to compare the okhttp2.x version to see, OKHTTP3 used to have those changes. Of course, look at this article before suggest to look at the previous article Android network programming (v) okhttp2.x usage full parse.
1. Preparation before use
Android Studio Configuration Gradle:
‘com.squareup.okhttp3:okhttp:3.2.0‘ ‘com.squareup.okio:okio:1.7.0‘
To add Network permissions:
<uses-permission android:name="android.permission.INTERNET"/>
2. Asynchronous GET requests
Custom, ask Baidu:
Private void getasynhttp() {mokhttpclient=NewOkhttpclient (); Request.builder Requestbuilder =NewRequest.builder (). URL ("Http://www.baidu.com");//Can be omitted, default is GET requestRequestbuilder.method ("GET",NULL); Request Request = Requestbuilder.build (); Call mcall= Mokhttpclient.newcall (request); Mcall.enqueue (NewCallback () {@Override Public void onfailure(Call call, IOException e) { }@Override Public void Onresponse(Call call, Response Response)throwsIOException {if(NULL! = Response.cacheresponse ()) {String str = response.cacheresponse (). toString (); LOG.I ("Wangshu","Cache---"+ str); }Else{Response.body (). String (); String str = Response.networkresponse (). toString (); LOG.I ("Wangshu","Network---"+ str); } runonuithread (NewRunnable () {@Override Public void Run() {Toast.maketext (Getapplicationcontext (),"Request succeeded", Toast.length_short). Show (); } }); } }); }
Unlike the 2.x version, the more depressing thing is that the callback is still not on the UI thread.
2. Asynchronous POST request
OKHTTP3 asynchronous POST request and okhttp2.x there are some differences that are not formencodingbuilder this class, instead it is a more powerful formbody:
Privatevoid Postasynhttp () {mokhttpclient=NewOkhttpclient (); Requestbody Formbody =NewFormbody.builder (). Add ("Size","Ten"). build ();Request Request=New Request. Builder (). URL ("Http://api.1-blog.com/biz/bizserver/article/list.do"). Post (Formbody). build ();Pager Pager= Mokhttpclient.newcall (Request);Pager. Enqueue (NewCallback () {@Override Publicvoid OnFailure (Pager Pager, IOException e) {} @Override Publicvoid Onresponse (Pager Pager,Response Response) throws IOException {Stringstr =Response. Body ().string();Log. I ("Wangshu", str); Runonuithread (NewRunnable () {@Override Publicvoid Run () {Toast.maketext (), Getapplicationcontext (),"Request succeeded", Toast.length_short). Show (); } }); } }); }
3. Uploading Files asynchronously
Uploading the file itself is also a POST request, the previous article did not say, here we fill. First define the upload file type:
publicstaticfinal MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
Upload the Wangshu.txt file of the SDcard root directory to the server:
Privatevoid Postasynfile () {mokhttpclient=NewOkhttpclient (); File File =NewFile ("/sdcard/wangshu.txt");Request Request=New Request. Builder (). URL ("Https://api.github.com/markdown/raw"). Post (Requestbody.create (Media_type_markdown, file)). build (); Mokhttpclient.newcall (Request). Enqueue (NewCallback () {@Override Publicvoid OnFailure (Pager Pager, IOException e) {} @Override Publicvoid Onresponse (Pager Pager,Response Response) throws IOException {Log. I ("Wangshu",Response. Body ().string()); } }); }
Of course if you want to change the upload file to sync, just call Mokhttpclient.newcall (request). Execute ().
There is a line in the Wangshu.txt file "Android Network programming (vi) OKHTTP3 usage full Resolution" We run the program click the Send File button, the final request for the network to return the result is the content of our TXT file:
Of course, don't forget to add the following permissions:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
4. Downloading files asynchronously
Download file also in the previous article did not mention, the implementation is relatively simple, here to download a picture, we get response after the stream is written in our designated image file will be.
Privatevoid Downasynfile () {mokhttpclient =NewOkhttpclient ();StringURL ="Http://img.my.csdn.net/uploads/201603/26/1458988468_5804.jpg";Request Request=New Request. Builder (). URL (URL). build (); Mokhttpclient.newcall (Request). Enqueue (NewCallback () {@Override Publicvoid OnFailure (Pager Pager, IOException e) {} @Override Publicvoid Onresponse (Pager Pager,Response Response) {InputStream InputStream =Response. Body (). ByteStream (); FileOutputStream FileOutputStream =NULL; try {FileOutputStream =NewFileOutputStream (NewFile ("/sdcard/wangshu.jpg")); byte[] Buffer =Newbyte[2048];int Len=0; while((Len= inputstream.read (buffer))! =-1) {fileoutputstream.write (buffer,0,Len); } fileoutputstream.flush (); } catch (IOException e) {Log. I ("Wangshu","IOException"); E.printstacktrace (); }Log. D ("Wangshu","File download succeeded"); } }); }
5. Uploading multipart files asynchronously
This scenario is very common, we sometimes upload files at the same time also need to pass other types of fields, OKHTTP3 implementation is very simple, it is important to note that no server received my multipart file, so here is just for example, the actual application of the actual work of the corresponding server.
First define the upload file type:
privatestaticfinal MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
private void Sendmultipart () {mokhttpclient = new okhttpclient ();Requestbody requestbody = new Multipartbody. Builder(). SetType(Multipartbody. FORM). Addformdatapart("title","Wangshu"). Addformdatapart("Image","Wangshu.jpg", Requestbody. Create(Media_type_png, New File ("/sdcard/wangshu.jpg"))). Build();Request Request = new Request. Builder(). Header("Authorization","Client-id"+"..."). URL("Https://api.imgur.com/3/image"). Post(Requestbody). Build();Mokhttpclient. Newcall(Request). Enqueue(New Callback () {@Override public void onfailure (Pager Pager, IOException e) {} @Override public void Onresponse (Pager Pager, Response Response) throws IOException {Log. I("Wangshu", response. Body(). String());} });}
6. Set the time-out and cache
and okhttp2.x difference is not through the okhttpclient directly set the timeout time and cache, but through the okhttpclient.builder to set up, through the builder configuration okhttpclient after Builder.build () to return okhttpclient, so we usually do not call new Okhttpclient () to get okhttpclient, but rather through Builder.build ():
File Sdcache = Getexternalcachedir ();int cacheSize =Ten*1024x768*1024x768;Okhttpclient. BuilderBuilder = new Okhttpclient. Builder(). ConnectTimeout( the, Timeunit. SECONDS). WriteTimeout( -, Timeunit. SECONDS). ReadTimeout( -, Timeunit. SECONDS). Cache(New Cache (Sdcache. Getabsolutefile(), cacheSize));Okhttpclient Mokhttpclient=builder. Build();
7. About cancellation requests and encapsulation
Cancel request can still call Call.cancel (), this does not change, I don't understand. Can view previous article Android network programming (v) okhttp2.x usage full analysis, here do not repeat, packaging on a also said that still recommend Okhttpfinal, it is currently based on OKHTTP3 for encapsulation.
8. About the source demo
The source demo is simple enough to test the contents of the four buttons above:
GitHub Source Download
Android Network Programming (vi) OKHTTP3 usage full analysis