A, OkHttp
1. Introduction to OkHttp
OkHttp is a third-party library for network requests, which encapsulates the bottom implementation of get, POST and other operations of network requests. It is one of the most popular network request frameworks on Android.
2. Use of OkHttp
In Android Studio, you don’t need to download a special JAR package. You can add a dependency directly to Gradle, as shown below:
compile 'com. Squareup. Okhttp3: okhttp: 3.10.0'
Copy the code
3, get method request
- Synchronous requests A synchronous request needs to be executed in a child thread and the UI is modified in the UI thread after the result of the execution is returned. Here is an example of code for a GET request:
new Thread(new Runnable() {
@Override
public void run() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("http:www.taobao.com").build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
Log.d("ABC"."response="+ response.body().toString()); // Go to the UI thread to modify UI}} catch (IOException e) {e.printStackTrace(); } } }).start();Copy the code
The GET synchronization request is divided into three steps: first, the OkHttpClient object is created using new. We then Call the newCall method of the OkHttpClient object to generate a Call object, which receives a Request object that stores our Request URL and Request parameters. Finally, execute the Call object to get the Response object, which is the result returned.
- Asynchronous request Asynchronous methods do not need to start a thread to perform the operation, but it is important to note that the final callback method is executed in the child thread, so UI changes must also be made in the UI thread. Take a look at this example:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("http://www.tabao.com").build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d("ABC"."error");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
Log.d("ABC"."response="+ response.body().toString()); // Go to the UI thread to modify UI}}});Copy the code
The GET asynchronous request consists of three steps: first, create an OkHttpClient object using new. We then Call the newCall method of the OkHttpClient object to generate a Call object, which receives a Request object that stores our Request URL and Request parameters. Finally, the enQueue method of the Call object is executed, which receives a Callback object and the Response object in the onResponse method of the Callback object. This is the result returned.
Summary: The difference between the synchronous and asynchronous methods of GET is that the synchronous method requires manual start of a thread, while the asynchronous method does not (in fact, it uses an internal thread).
4, post method request
- A post request is almost identical to a GET request, as shown in the following example:
new Thread(new Runnable() {
@Override
public void run() {
OkHttpClient client = new OkHttpClient();
FormBody.Builder formBody = new FormBody.Builder();
formBody.add("bookName"."Android Art");
Request request = new Request.Builder().url("http:www.taobao.com").post(formBody.build()).build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
Log.d("ABC"."response="+ response.body().toString()); // Go to the UI thread to modify UI}} catch (IOException e) {e.printStackTrace(); } } }).start();Copy the code
Contrast: The difference between a POST Request and a GET Request is that a POST (RequestBody) method is used to generate a Request object. A subclass of the RequestBody object is FormBody. So you can use the FormBody object to create key-value pair parameters.
Taking this a step further, why do POST requests need to execute the POST method, but GET requests don’t? So let’s see what’s going on in the POST method, okay?
public Builder post(RequestBody body) {
return method("POST", body);
}
Copy the code
Returns the result of executing the method, passing a “POST” string. Take a look at the method execution:
public Builder method(String method, RequestBody body) {
if (method == null) throw new NullPointerException("method == null");
if (method.length() == 0) throw new IllegalArgumentException("method.length() == 0");
if(body ! = null && ! HttpMethod.permitsRequestBody(method)) { throw new IllegalArgumentException("method " + method + " must not have a request body.");
}
if (body == null && HttpMethod.requiresRequestBody(method)) {
throw new IllegalArgumentException("method " + method + " must have a request body.");
}
this.method = method;
this.body = body;
return this;
}
Copy the code
The “POST” string is passed to the Method variable of the Builder object, which is assigned a value of “GET” in the Builder’s default constructor. The Request.Builder object is created as a get Request by default, so the get Request does not need to set the get method, and the POST Request needs to change the method variable to “POST”.
- A post request is similar to a GET request. The difference is also the same for synchronous requests, so let’s look at examples:
OkHttpClient client = new OkHttpClient();
FormBody.Builder formBody = new FormBody.Builder();
formBody.add("bookName"."Android Art");
Request request = new Request.Builder().url("http://www.tabao.com").post(formBody.build()).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d("ABC"."error");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
Log.d("ABC"."response="+ response.body().toString()); // Go to the UI thread to modify UI}}});Copy the code
Second, the Retrofit
1. Introduction to Retrofit
Retrofit is a RESTful HTTP Web request framework that is based on OkHttp. It is annotated to configure network parameters, supports parsing and serialization of various types of data (Gson, Json, Xml, etc.), and also supports RxJava. Below is the Retrofit and OkHttp figure (figure from https://blog.csdn.net/carson_ho/article/details/73732076) :
2. Use of Retrofit
2.1 Adding a dependent Library
The Retrofit library dependencies in Android Studio, which also rely on the OkHttp library, need to be added as well.
compile 'com. Squareup. Retrofit2: retrofit: 2.1.0'
compile 'com. Squareup. Okhttp3: okhttp: 3.8.1'
Copy the code
2.2 Adding an Interface for Network Request
Retrofit uses annotations to describe and configure network request parameters. You actually translate the annotation into an Http request using a dynamic proxy, and then execute the request. The basic structure is as follows:
public interface GitHubService {
@GET("getUserData")
Call<User> getCall();
}
Copy the code
User.java
public class User {
private int userId;
private String userName;
private ExInfo exInfo;
private static class ExInfo {
private String from;
private String birthDay;
}
public void show() {
Log.d("ABC"."userId=" + userId);
Log.d("ABC"."userName=" + userName);
Log.d("ABC"."from=" + exInfo.from);
Log.d("ABC"."birthday="+ exInfo.birthDay); }}Copy the code
This is an Interface, not a class. 2. Different interface methods can be created. 3. Each interface method and its parameters must be annotated; otherwise, an error will be reported. 4. Request methods include GET, POST, PUT, HEAD, DELETE, etc. The return type of the method must be Call, and XXX is the class that receives the data (either our custom class or ResponseBody). 6. The field name in User must be the same as the field name defined in the background Json so that Json can be successfully parsed.
2.3 Creating Retrofit Objects
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://10.75.114.138:8081/") .addConverterFactory(GsonConverterFactory.create()).build(); / / set the network request Url. AddConverterFactory (GsonConverterFactory. The create ()) / / set data parser. The build ();Copy the code
Address of the network request: Annotations set by baseUrl() + network request interface when creating Retrofit objects. AddConverterFactory (GsonConverterFactory. The create ()) is used to set data parser, it can parse Gson, JsonObject, JsonArray these three format of the data.
2.4 Creating a Network Request Interface instance
GitHubServiceRequest Request = retrofit.create(githubservice.class); Call<Reception> Call = request.getCall();Copy the code
2.5 Sending network Requests
Synchronous request:
Response<Reception> Response = call.execute();Copy the code
Asynchronous request:
Call. Enqueue (new Callback<User>() {@override public void onResponse(call <User> call, Response.body (); response.body();if(user ! = null) { user.show(); @override public void onFailure(Call<User> Call, Throwable Throwable) {system.out.println ("Request failed"); }});Copy the code
3, summarize
Retrofit is a RESTful web request framework that is implemented in OkHttp at the next level, so the principle is the same as OkHttp, but a layer is encapsulated on top of OkHttp to make the request interface and data parsing more concise.