In those years I've used Android library network requests

Here's what I used network frameworks, each has its own merits and demerits, their application to more scene selection.

Test using a test query interface ip address: http: //ip.tianqiapi.com ip = xxx.xxx.xxx.xxx? .
In Android points to note requesting network problems:
1. Permissions: <uses-permission android:name="android.permission.INTERNET"/>.
2. The main thread can request the network, it will be given.
3. In the sub-thread can not operate UI, an error.
4. In order to ensure data security, can not be used in Android P http, want to change to https, but by increasing the android application tag in the AndroidManifest.xml file: usesCleartextTraffic = "true" to avoid forcing https, of course, there are other ways, not just one of but one kind is enough. (Or recommend their service upgraded to https).

A, HttpURLConnection

The first is to say that undoubtedly HttpURLConnection, he began learning network programming in java stage.

First constructed URL, the URL is opened HttpURLConnection, read data stream using the IO, which is the most basic operation. It can be more setRequestMethod ( "GET") to modify the request type. Other types of operation is very troublesome.

 @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     new Thread() {
         @Override
         public void run() {
             super.run();
             doHttpURLConnection("http://ip.tianqiapi.com?ip=39.156.66.18");
         }
     }.start();
 }
private void doHttpURLConnection(String u){
    try {
        URL url =new URL(u);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        InputStreamReader inputStreamReader =new InputStreamReader(urlConnection.getInputStream());
        BufferedReader bufferedReader =new BufferedReader(inputStreamReader);
        String temp="";
        StringBuffer stringBuffer =new StringBuffer();
        while ((temp=bufferedReader.readLine())!=null){
         stringBuffer.append(temp);
        }
        Log.i(TAG, "doHttpURLConnection: "+stringBuffer);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Two, Okhttp

Next is Okhttp, is the fire of a network library, provided by the company Square. There are many advantages, such as the use of cache in response to network requests to avoid duplication, has interceptor etc., Address: https: //github.com/square/okhttp.

The first is the introduction of his latest is 4.3.1.

 implementation("com.squareup.okhttp3:okhttp:4.3.1")

API is very easy to use, is first constructed OkHttpClient, global initialized only once, the object can be constructed by an internal Builder set parameters, such as read timeout period, followed by () request object constructed by Request.Builder, if a Get request, direct use .get (), if the request is Post, use .post (requestBody), which also passed requestBody objects can be created by the static method requestBody create, you can also use one of its subclasses, such as FormBody.

Okhttp requests into synchronous and asynchronous, synchronous if it is, use OhttpClitent.execute (), if it is asynchronous, will have to use enqueue (), and pass the callback address.

Callback is a callback interface, including two methods, the callback failures and successes onFailure callback onResponse, by response.body () can get responseBody response object, the simplest method by converting into ResponseBody.string string, not toString () !!!, If there is no response header Content Type, using UTF8 encoding, encoding otherwise specified, but be aware that, string method can only be called once, after calling Okhttp will release resources, so the second call error. If the response object is too large, it may cause OutOfMemoryError

 private void dpOkHttp(String u){
     OkHttpClient httpClient =new OkHttpClient();
     FormBody body =new FormBody.Builder().build();
     Request request =new Request.Builder()
             .url(u)
             .post(body)
             .build();
     String string = null;
     //同步
     try {
         string = httpClient.newCall(request).execute().body().string();
         Log.i(TAG, "dpOkHttp: "+string);
     } catch (IOException e) {
         e.printStackTrace();
     }
     
     //异步
     httpClient.newCall(request).enqueue(new Callback() {
         @Override
         public void onFailure(@NotNull Call call, @NotNull IOException e) {
         }
         @Override
         public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
             Log.i(TAG, "onResponse: "+response.body().string());
         }
     });
 }

Three, okhttputils

This is Zhang Hong Yang Great God Okhttp library package, before the time of writing demo is often used, it is also very simple. Specific details can be viewed using https://github.com/hongyangAndroid/okhttputils. Note that version to correspond.

implementation 'com.zhy:okhttputils:2.6.2'
implementation("com.squareup.okhttp3:okhttp:3.3.1")
private  void doOkhttpUtil(String u){
    OkHttpClient httpClient =new OkHttpClient.Builder()
            .build();
    OkHttpUtils.initClient(httpClient);
    OkHttpUtils.get()
            .url(u)
            .build()
            .execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    e.printStackTrace();
                }
                @Override
                public void onResponse(String response, int id) {
                    Log.i(TAG, "onResponse: "+response);
                }
            });
}

Four, Volley

Published on Goole I / O 2013 network communication libraries, the advantage is automatic scheduling network request, the priority support requests, support cancellation request can be canceled or more single request, and the like, in the case of data communications, but not frequent case , jar package size is very small, and Volley callback time is in the main thread, can be directly manipulated UI, okhttputils also in the main thread, but Okhttp not, need to be addressed by the Handler. There are also disadvantages, such as file downloads and general image loading.

This can be to https://developer.android.google.cn/training/volley Detailed view.

The first is to build RequestQueue request queue, a global initialization only just once, and then build StringRequest, ImageRequest, ClearCacheRequest, JsonRequest four subclasses Request request object, there. A tag may be provided to the Request, and by RequestQueue.cancelAll (tag) can be canceled. `

implementation 'com.android.volley:volley:1.1.1'
 private void doVolley(String u) {
     RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
     StringRequest stringRequest = new StringRequest(Request.Method.GET,u, new Response.Listener<String>() {
         @Override
         public void onResponse(String response) {
             Log.i(TAG, Thread.currentThread().getName()+" onResponse: " + response);
         }
     }, new Response.ErrorListener() {
         @Override
         public void onErrorResponse(VolleyError error) {
         }
     });
     stringRequest.setTag("tag");
     Request<String> request = requestQueue.add(stringRequest);
     requestQueue.cancelAll("tag");
 }

Five, Retrofit

This is the first Square of the company, also based Okhttp expand, eventually completed by the Okhttp network requests, and is responsible for Retrofit package interface request. I have been using this.

His address https://square.github.io/retrofit/ or https://github.com/square/retrofit

Retrofit whole operation relies on notes and interfaces to complete, the wording is different from the above are four very style.

implementation("com.squareup.okhttp3:okhttp:3.3.1")
implementation 'com.squareup.retrofit2:retrofit:2.7.1'

First, create an interface, return value Call <T> In, @ GET ( "/") represents the request path, @ Query parameter, i.e.? Following data

public interface Apis {
    @GET("/")
    Call<ResponseBody> getIpAddress(@Query("ip")String ip);
}

Then you can request the following way, which Retrofit and Apis do not every request to create, create objects using dynamic proxy to return a proxy of Apis. Retrofit Construction To indicate when the host address baseUrl, will splice the values ​​@ Get, @ Post isochronous requests.

  private void doRetrofit(String u) {
      OkHttpClient okHttpClient = new OkHttpClient();
      Retrofit retrofit = new Retrofit.Builder()
              .client(okHttpClient)
              .baseUrl("http://ip.tianqiapi.com/")
              .build();
      Apis apis = retrofit.create(Apis.class);
      apis.getIpAddress("39.156.66.18").enqueue(new retrofit2.Callback<ResponseBody>() {
          @Override
          public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
              try {
                  Log.i(TAG, "onResponse: " + response.body().string());
              } catch (IOException e) {
              }
          }
          @Override
          public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
          }
      });
  }

Many also notes:
Request mode Notes: GET, POST, PUT, DELETE , PATCH, HEAD, OPTIONS, HTTP
mark notes: FormUrlEncoded, Multipart, Streaming
parameter type annotation: Headers, Header, Body, Field , FieldMap, Part, PartMap, Query, QueryMap, Path
with these annotations can complete the file upload, Post submitted json and other requests.

Is more practical converter that can convert the object into a string json by him. If there is no converter, the return value must always be ResponseBody.
Introducing dependent, internal com.google.gson process.

implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

IpAddress。

public class IpAddress {
    private String ip;
    private String country;
    private String province;
    private String city;
    private String isp;

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getIsp() {
        return isp;
    }

    public void setIsp(String isp) {
        this.isp = isp;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    @Override
    public String toString() {
        return "IpAddress{" +
                "ip='" + ip + '\'' +
                ", country='" + country + '\'' +
                ", province='" + province + '\'' +
                ", city='" + city + '\'' +
                ", isp='" + isp + '\'' +
                '}';
    }
}

Modify the return value.

public interface Apis {
    @GET("/")
    Call<IpAddress> getIpAddress(@Query("ip")String ip);
}
 private void doRetrofit(String u) {

        OkHttpClient okHttpClient = new OkHttpClient();

        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(u)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Apis apis = retrofit.create(Apis.class);
        apis.getIpAddress("39.156.66.18").enqueue(new retrofit2.Callback<IpAddress>() {
            @Override
            public void onResponse(retrofit2.Call<IpAddress> call, retrofit2.Response<IpAddress> response) {
                Log.i(TAG, "onResponse: " + response.body().toString());

            }

            @Override
            public void onFailure(retrofit2.Call<IpAddress> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

Output follows very convenient
Here Insert Picture Description

Published 42 original articles · won praise 7 · views 7741

Guess you like

Origin blog.csdn.net/HouXinLin_CSDN/article/details/104353766