English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Okhttp in Android3Implementation of Uploading Multiple Images While Passing Parameters

Previously, images were uploaded directly by converting the image to an IO stream and passing it to the server without using a framework to pass the image.

Recently, I plan to change the method of uploading images while doing a project.

With the development of Android to the present, Okhttp is becoming more and more important, so, this time I choose to upload images using Okhttp.

Okhttp has now been updated to Okhttp3Versioned, compared with the previous version, there are also some differences. I have found a lot of information on the Internet,

And debug with java backend colleagues repeatedly, finally successfully uploaded multiple images, and passed some key-value parameters.

The following is the encapsulation of the process:

private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
/**
   * Upload multiple images and parameters
   * @param reqUrl URL address
   * @param params Parameters
   * @param pic_key Keyword for uploading image
   * @param paths Image path
   */
  public Observable<String> sendMultipart(String reqUrl,Map<String, String> params,String pic_key, List<File> files){
    return Observable.create(new Observable.OnSubscribe<String>(){
      @Override
      public void call(Subscriber<? super String> subscriber) {
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
        multipartBodyBuilder.setType(MultipartBody.FORM);
        //Traverse all parameters in the map to the builder
        if (params != null){
          for (String key : params.keySet()) {
            multipartBodyBuilder.addFormDataPart(key, params.get(key));
          }
        }
        //Traverse all absolute paths of images in paths to builder, and agree on keys such as "upload" as the key accepted by the background for multiple images
        if (files != null){
          for (File file : files) {
            multipartBodyBuilder.addFormDataPart(pic_key, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
          }
        }
        //Build request body
        RequestBody requestBody = multipartBodyBuilder.build();
        Request.Builder RequestBuilder = new Request.Builder();
        RequestBuilder.url(reqUrl);// Add URL address
        RequestBuilder.post(requestBody);
        Request request = RequestBuilder.build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
          @Override
          public void onFailure(Call call, IOException e) {
            subscriber.onError(e);
            subscriber.onCompleted();
            call.cancel();
          }
          @Override
          public void onResponse(Call call, Response response) throws IOException {
            String str = response.body().string();
            subscriber.onNext(str);
            subscriber.onCompleted();
            call.cancel();
          }
        });
      }
    });
  } 

Call in UI interface:

OkHttp3Utils.getInstance().sendMultipart(Constants.URL.URL_ADD_NOTICE, mMap, "appendix", mImageList)
        .observeOn(AndroidSchedulers.mainThread())
        .subscribeOn(Schedulers.newThread())
        .subscribe(new Subscriber<String>() {
          @Override
          public void onCompleted() {
          }
          @Override
          public void onError(Throwable throwable) {
            LogUtil.i(TAG, "throwable:\ + throwable.toString());
          }
          @Override
          public void onNext(String s) {
            LogUtil.i(TAG, "s:\ + s);
          }
        }); 

During the debugging process, once I mistakenly wrote multipartBodyBuilder.addFormDataPart(pic_key, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file)); as multipartBodyBuilder.addFormDataPart(pic_key, null, RequestBody.create(MEDIA_TYPE_PNG, file)); which caused the background to be unable to obtain the image using conventional methods (although the image data could also be seen during breakpoint debugging), this point needs to be paid attention to.

That's all for this article. I hope it will be helpful to everyone's learning, and I also hope everyone will support the Yell Tutorial.

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report violations, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like