SoFunction
Updated on 2025-04-07

Android uses OkHttp to download and upload pictures

This article shares the specific code for OkHttp to download and upload pictures for your reference. The specific content is as follows

public class MainActivity extends AppCompatActivity {

  private String Path = "/eth/ajNVdqHZLLAxibwnrOxXSzIxA76ichutwMCcOpA45xjiapneMZsib7eY4wUxF6XDmL2FmZEVYsf86iaw/";
  private static final int SUCCESS = 993;
  private static final int FALL = 814;
  Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      switch () {
        //The network is loaded successfully, the UI is updated, and the obtained image resources are processed        case SUCCESS:
          //Get the byte array through message          byte[] Picture = (byte[]) ;
          //Use the BitmapFactory factory to convert the byte array into bitmap          Bitmap bitmap = (Picture, 0, );
          //Set the picture through ImageView          mImageView_okhttp.setImageBitmap(bitmap);
          break;
        // When the network loading fails, the logical code executed        case FALL:
          (, "Network exception", Toast.LENGTH_SHORT).show();
          break;

        default:
          break;
      }
    }
  };
  private ImageView mImageView_okhttp;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView(.activity_main);
    //Initialize the control    initView();
  }

  private void initView() {
    mImageView_okhttp = (ImageView) findViewById(.imageView_okhttp);
  }

  /**
    * Obtain the image resources on the network based on the click event, using the OKhttp framework
    *
    * @param view
    */
  public void Picture_okhttp_bt(View view) {
    //1. Create OKhttpClient object    OkHttpClient okHttpClient = new OkHttpClient();
    //2. Create a Request object, set parameters, and if the request method is get, you don't need to set it. The default is get    Request request = new ()
        .url(Path)//Set the request URL        .build();//Create a request object    //3. Create a Call object with the parameter request object and send a request    Call call = (request);
    //4. Asynchronous request, request to join the schedule    (new Callback() {
      @Override//Request failed callback      public void onFailure(Call call, IOException e) {
        (FALL);
      }

      @Override//Request successfully callback      public void onResponse(Call call, Response response) throws IOException {
        //Get to get resources from the Internet and convert them to the type we want        byte[] Picture_bt = ().bytes();
        //Update the UI through handler        Message message = ();
         = Picture_bt;
         = SUCCESS;
        (message);

      }
    });
  }

  //When the button is clicked, use OKhttp to upload the image to the server (/tangxl2008008/article/details/51777355)  //Note: Sometimes the upload of images fails, and the server stipulates that a key must be uploaded. If there is a problem with the network during development, communicate more with the interviewer.  public void uploading(View view) {
    //Picture upload interface address    String url = "https:///sell/";
    //Create upload file object    File file = new File((), "");

    //Create RequestBody encapsulation parameters    RequestBody fileBody = (("application/octet-stream"), file);
    //Create MultipartBody and set RequestBody    MultipartBody multipartBody = new ()
        .setType()
        .addFormDataPart("image", "", fileBody)
        .build();
    //Create Request    Request request = new ()
        .url(url)
        .post(multipartBody)
        .build();

    //Create an okhttp object    OkHttpClient okHttpClient = new ()
        .connectTimeout(10, )
        .readTimeout(10, )
        .writeTimeout(10, )
        .build();

    //After uploading the picture, you will get the server feedback data    (request).enqueue(new Callback() {
      @Override
      public void onFailure(Call call, IOException e) {
        ("ff", "uploadMultiFile() e=" + e);
      }

      @Override
      public void onResponse(Call call, Response response) throws IOException {
        ("ff", "uploadMultiFile() response=" + ().string());
      }
    });


  }

}

activity_main.xml

<RelativeLayout
  xmlns:andro
  xmlns:tools="/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".picture_okhttp.MainActivity">


  <Button
    android:
    android:onClick="Picture_okhttp_bt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Download Picture"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="59dp"/>

  <Button
    android:text="Upload pictures"
    android:onClick="uploading"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:
    android:layout_alignParentTop="true"
    android:layout_alignLeft="@+id/button"
    android:layout_alignStart="@+id/button"/>

  <ImageView
    android:
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"/>

</RelativeLayout>

//rely

implementation '.okhttp3:okhttp:3.4.2'

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.