First, preface
Since the beginning of Android4.4, Google has begun to replace the source of HttpURLConnection with Okhttp, and in the SDK after Android6.0, Google has removed support for httpclient, and the popular retrofit on the market is also The okhttp is used to encapsulate it again. Thus see the importance of learning okhttp.
This article is based on the current latest version of 3.5.0 as an example (2.0 and above version and 3.0 version of the large differences, this article does not do in-depth discussion, please self-Baidu), using the Android Stuido as a development environment, to lead everyone simple familiar with the use of okhttp. As one of the "Android Network Programming" series of articles, the following article will be a gradual in-depth discussion around OKHTTP3. This article we want to achieve the purpose is: do not drill down, simple and clear, you can paste the copy directly.
II. Preparation before use 2.1 official documents
To know that learning a new technology, the best information is always the official document:
Okhttp Official Introduction
GitHub source
2.2 Android Studio Configuration Gradle Environment:
compile ‘com.squareup.okhttp3:okhttp:3.5.0‘compile ‘com.squareup.okio:okio:1.11.0‘
2.3 Adding network permissions
Do not forget to add permissions Ah, this is often overlooked in the development of the place
<uses-permission android:name="android.permission.INTERNET"/>
Iii. using the Tutorial 3.1 Http Get3.1.1 asynchronous get
The most common in the HTTP request is the Get method, in most of the usage scenarios, we use the asynchronous GET request, the following we are using okhttp asynchronous get to request the homepage of Baidu.
Step 1: Create a Okhttpclient object okhttpclient okhttpclient =New Okhttpclient ();Step 2: Create a request that does not specify a request method when the default is get. Request.builder Requestbuilder =New Request.builder (). URL ("Http://www.baidu.com");Can be omitted, the default is GET request Requestbuilder.method ("GET",NULL);Step 3: Create a Call objectcall call = Okhttpclient.newcall (RequestBuilder.build ()); Span class= "Hljs-comment" >//step 4: Start asynchronous request call.enqueue (new Callback () {@Override public void onfailure (call call, IOException e) {//todo:17-1-4 request failed} @Override public void Onresponse (call call, Response Response) throws ioexception {//todo:17-1-4 request succeeded //obtains the return body responsebody BODY = response.body (); } });
The above is the main step of sending an asynchronous get request. First we want to create a OkHttpClick
and Request.Builder()
object, and then url()
set the network address through the method to specify the target of the access, not only is the Request.Builder()
support chain programming (return body is the ontology) here can set these methods OH:
Request.builder () chained programming, not discussed here
Next we will OkHttpClick
set up the object with the object to Request
establish a contact, the method used to okHttpClick
newCall()
get an object, the function of the call Call
object is equivalent to the request encapsulated as a task, since it is a task, there will naturally be execute () and Cancel () methods.
Finally, we want to execute the request asynchronously, so we're calling Call.enqueue, adding call to the dispatch queue, and waiting for the task to finish, we can get the result in callback. However, it is important to note that call callback is a child thread, so it is not possible to manipulate the interface directly. You need to handle it on your own. When the request succeeds, the callback onResponse()
method is called, and we can see that the returned result is an Response
object, where we are concerned with the return body body
(type) in the request ResponseBody
, and most of the time we want to get the string for JSON parsing to get the data. So you can body.string()
get the string in a way.
Responsebody's API
See ResponseBody
the API documentation to see, you body
can also get byte[], Reader, InputStream, one of the most surprising is that you can return to InputStream, which at least shows that okhttp can support the download of large files, This way we can easily use InputStream for the I/O mode of file writing!!!
Let's make it a little bit:
Step 1: The first step unchanged create Okhttpclick okhttpclient okhttpclient =New Okhttpclient ();Step 2: Create Requset Request request =New Request.builder (). URL ("Http://www.ssyer.com/uploads/org_2017010593503_775.jpg"). Build ();Step 3: Establish a contact to create a call Mokhttpclient.newcall (request). Enqueue (New Callback () {@OverridePublicvoid OnFailure (PagerCall, IOException e) {} @OverridePublicvoid Onresponse (PagerCall, Response Response) {InputStream InputStream = Response.body (). ByteStream (); FileOutputStream FileOutputStream =Nulltry {FileFile =NewFile (environment.getexternalstoragedirectory () + "big lion. jpg") FileOutputStream = new FileOutputStream ( file); byte[] buffer = new byte[2048]; int len = 0; While (len = InputStream. Read (buffer))! =-1) {FileOutputStream. Write (buffer, 0, Len);} fileoutputstream.flush (); } catch (IOException e) {e.printstacktrace ();} LOG.D ("Downloadasynfile", "file download succeeded");});
3.1.1 Synchronous get
Get
It also supports blocking-mode synchronization requests, but this approach is rarely used in development. We've also said that call has a execute()
method that you can also invoke directly to call.execute()
return one Response
. Then isSuccessful()
, the results are resolved by the successful interpretation.
3.2 Asynchronous HTTP Post
After looking at the Get
request method, I believe that your use of the request is also used in the basic grasp, using Post
the method and Get
although there are some differences, but the essence is unchanged. So let's take the example of carrying key-value pairs Post
first, and familiarize yourself with Post
the use of the method.
3.2.1 Post Upload key value pair
Step 1: The same need to create a Okhttpclick object okhttpclient okhttpclient =New Okhttpclient ();Step 2: Create Formbody.builder formbody formbody =New Formbody.builder (). Add ("Name","DSD"). Build ();Step 3: Create a request for requests requestNew Request.builder (). URL ( "http://www.baidu.com"). Post (Formbody). build (); //step 4: Establish a contact to create a Call object Okhttpclient.newcall (Request). Enqueue ( new Callback () { @Override public Span class= "hljs-function" >void onfailure (call call, IOException e) {//TODO: 17-1-4 request failed} @Override public void onresponse (call call, Response Response) throws ioexception {// Todo:17-1-4 request succeeded});
is not Get
very similar AH. It is well known that Post
when used, the parameters are contained in the request body. So we pass FormBody
, add multiple string key value pairs, and then Request
post(formBody)
Complete our construction for the addition Request
. The next step is the same as the get step, is not very simple ah!
3.2.2 Post Asynchronous Upload file
Directly on the code
Step 1: Create a Okhttpclient object okhttpclient okhttpclient =New Okhttpclient ();Step 2: Create the Requestbody and the required parameters2.1 Getting filesFileFile =NewFile (environment.getexternalstoragedirectory () +"Test.txt");2.2 Create MediaType settings upload file type mediatype mediatype = Mediatype.parse ("Text/plain; Charset=utf-8 ");2.3 Get request body requestbody Requestbody = requestbody.create (mediatype,file);//step 3: Create a request to ask request = new request.builder (). URL ( Span class= "hljs-string" > "http://www.baidu.com"). Post (Requestbody). build (); //step 4 Establish contact Okhttpclient.newcall (request). Enqueue (new Callback () {@Override public void onfailure (call call, IOException e) {//todo:17-1-4 request failed} @Override public void Onresponse (call call, Response Response) throws ioexception {//todo:17-1-4 request success});
Of course here need to add permission drops, you have not forgotten it.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
The first step is the same as before, but the second step starts with a certain difference. In Step2 we need to MediaType.parse("text/plain; charset=utf-8")
set a certain type (MIME) for the upload file here we upload the plain text file so choose the "text/plain
type, and the encoding format is utf-8
. Below is a list of common file types that are easy to use.
Parameters |
Description |
Text/html |
HTML format |
Text/plain |
Plain Text Format |
Text/xml |
XML format |
Image/gif |
GIF picture format |
Image/jpeg |
JPG image format |
Image/png |
PNG image format |
Application/xhtml+xml |
XHTML format |
Application/xml |
XML data format |
Application/atom+xml |
Atom XML Aggregation format |
Application/json |
JSON data format |
Application/pdf |
PDF format |
Application/msword |
Word Document Format |
Application/octet-stream |
Binary Stream data |
In fact MIME file type special approval many, interested friends can be see the MIME reference manual on W3school.
Upload type
In the creation RequestBody
of the time can be seen, we can not only upload file files, can also upload String
, ByteString
byte
array and other types, where the upload byte data can choose three parameters of the Creta method, you need to specify the offset and the byte length to write, Haha this is not a description can be directly multithreaded, breakpoint upload! Through these types, we can upload JSON strings, pictures and other content is really convenient and useful ah.
Summarize
After the introduction of the above I believe that we have a certain understanding of okhttp simple use, OKHTTP3 is not very simple to use it, but every step of the request has a lot of repetition of the place, which if in the actual development, not to people tired ah, the spirit of Saving (TOU) weeks (LAN) period of the purpose , cough, the following article will further lead you to learn OKHTTP3 advanced usage and Okhttp tool class packaging Oh, please look forward to.
Reference:
- Https://github.com/square/okhttp
- Android okhttp Full parsing It's time to get to know okhttp.
(Original address: http://www.jianshu.com/p/7d88613c0b0f)
Go OKHTTP3 's most nutritious beginner's tutorial