android uses OkHttp to upload multiple pictures of the implementation code

  • 2021-09-16 08:10:29
  • OfStack

Brief introduction

Let's talk about why OkHttp is used as a framework for uploading multiple pictures. There are two reasons:

1. OkHttp can be used as the underlying transmission protocol of Volley, which is faster

2. There is a small problem in uploading pictures with Xutils and KJFramework. First of all, you can upload, and you can upload multiple pictures and other parameters. What is the problem? It is inflexible to accept parameters in the background, Xutlis and KJFramework use HashMap to upload each parameter, Every picture must also have an key with only one. To upload a picture, you need to define a parameter to receive it. To upload two pictures, you need to define two parameters to receive them. When the number of uploaded pictures is uncertain, such as 9 or 16 at most, 9 or 16 pictures should be defined when the background accepts pictures, which is not conducive to expansion. It is best to receive all pictures with one parameter, instead of defining many parameters because of this uncertain problem, and then judging whether they exist one by one. This is not the case at the bottom of OkHttp. I roughly browsed the source code. When receiving parameters at the bottom, I used List. As long as I use the same key, I can add it to the same list, while the background only needs to traverse continuously according to this one key. No matter how many pictures are barrier-free, there is no worries.

Core code implementation


// Parameter type 
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
// Create OkHttpClient Instances 
private final OkHttpClient client = new OkHttpClient();
MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);
// Traversal map All parameters in the builder
for (String key : map.keySet()) {
      builder.addFormDataPart(key, map.get(key));
    }
  // Traversal paths The absolute path of all pictures in the builder , and agreed that key Such as " upload "Accepting multiple pictures in the background key
    for (String path : paths) {
      builder.addFormDataPart("upload", null, RequestBody.create(MEDIA_TYPE_PNG, new File(path)));
    }
   // Build the request body 
    RequestBody requestBody = builder.build();
 // Build request 
 Request request = new Request.Builder()
        .url(url)// Address 
        .post(requestBody)// Add Request Body 
        .build(); 
// Send asynchronous requests, synchronization will report errors, Android4.0 Time-consuming operations in the main thread are prohibited in the future 
client.newCall(request).enqueue(new Callback() {
      @Override
      public void onFailure(Request request, IOException e) {
        System.out.println("request = " + request.urlString());
        System.out.println("e.getLocalizedMessage() = " + e.getLocalizedMessage()) ; 
      }
      @Override
      public void onResponse(Response response) throws IOException {
        // See clearly is response.body().string() No response.body().toString()
             System.out.println("response = " + response.body().string());
             }
    });

This is the basic implementation of ideas, more please refer to the OkHttp documentation, the project I am prepared to completely remove other parts of Xutils, such as the file download part.

Knowledge expansion

Difference between List and HashMap

List can hold multiple identical or different elements

HashMap holds elements as key-value pairs (key-value). When multiple elements with the same key are added, the previous elements will be overwritten

This point is very important. The design of Xutils and KJFframework does not take this point into account, which seems to be very easy to use. However, when I want to add multiple identical or different picture files as parameters and transmit them to the background, I need to define a lot of key, otherwise no matter how many pictures are added, the result can only be the last one.

Summarize


Related articles: