The simple use of OkHttp

Open source prevalent today, many excellent network communication libraries may be used instead HttpURLConnection native, and today we introduce the simple use under OkHttp.
OkHttp project's home page address is: http://github.com/square/okhttp .
Before using OkHttp, we need to add a dependency OkHttp library.

compile 'com.squareup.okhttp3:okhttp:3.4.1'

Adding the two libraries rely automatically download, is OkHttp a library, a library is Okio, which is the basis of the former communication.
Then we come to the question, talk about OkHttp specific usage.
A, instantiates an instance of a OkHttpClient.
Second, if you want to send an HTTP request, you need to create a Request object.

OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder()
             .url("http://www.baidu.com")
              .build();

We can put together a number of ways before the final build () method to enrich the Request object, where we set goals through URL () method of network address.
Third, call OkHttpClient of newCall () method to create a Call object, and call its execute () method to send the request and obtain the data returned by the server.

 Response response=client.newCall(request).execute();

Response object is returned by the server data, we obtain the specific content returned by the following method.

String responseData=response.body().string();

Here the rest of the code, and I'm on a blog as well, so other code that you can read my previous blog.

Mentioned above is to get data from the server, then we talk about how the submission of data to the server with OkHttp.

First, the first build object to hold a RequestBody parameter to be submitted, as follows:

RequestBody requestbody=new FormBody()
      .add("username","admin")
      .add("password","123456")
      .build();

Second, in what is called Request.Builder post () method, and RequestBody incoming objects:

Request request=new Request.Builder()
     .url("http://www.baidu.com")
     .post(requestBody)
     .build();

Third, calls execute () method to send the request and obtain data returned by the server.

If you feel the need to understand the source code, please add my micro letter.Write pictures described here

Published 37 original articles · won praise 10 · views 10000 +

Guess you like

Origin blog.csdn.net/OneLinee/article/details/78369405