溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在Android中利用OkHttp實現(xiàn)一個圖片上傳下載功能

發(fā)布時間:2021-03-08 14:27:08 來源:億速云 閱讀:305 作者:Leah 欄目:移動開發(fā)

怎么在Android中利用OkHttp實現(xiàn)一個圖片上傳下載功能?針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

具體內(nèi)容如下

MainActivity.java

public class MainActivity extends AppCompatActivity {

  private String Path = "https://10.url.cn/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 (msg.what) {
        //加載網(wǎng)絡(luò)成功,進(jìn)行UI的更新,處理得到的圖片資源
        case SUCCESS:
          //通過message,拿到字節(jié)數(shù)組
          byte[] Picture = (byte[]) msg.obj;
          //使用BitmapFactory工廠,把字節(jié)數(shù)組轉(zhuǎn)換為bitmap
          Bitmap bitmap = BitmapFactory.decodeByteArray(Picture, 0, Picture.length);
          //通過ImageView,設(shè)置圖片
          mImageView_okhttp.setImageBitmap(bitmap);
          break;
        //當(dāng)加載網(wǎng)絡(luò)失敗,執(zhí)行的邏輯代碼
        case FALL:
          Toast.makeText(MainActivity.this, "網(wǎng)絡(luò)異常", Toast.LENGTH_SHORT).show();
          break;

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

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //初始化控件
    initView();
  }

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

  /**
   * 根據(jù)點擊事件獲取絡(luò)上的圖片資源,使用的是OKhttp框架
   *
   * @param view
   */
  public void Picture_okhttp_bt(View view) {
    //1. 創(chuàng)建OKhttpClient對象
    OkHttpClient okHttpClient = new OkHttpClient();
    //2.建立Request對象,設(shè)置參數(shù),請求方式如果是get,就不用設(shè)置,默認(rèn)使用的就是get
    Request request = new Request.Builder()
        .url(Path)//設(shè)置請求網(wǎng)址
        .build();//建立request對象
    //3.創(chuàng)建一個Call對象,參數(shù)是request對象,發(fā)送請求
    Call call = okHttpClient.newCall(request);
    //4.異步請求,請求加入調(diào)度
    call.enqueue(new Callback() {
      @Override//請求失敗回調(diào)
      public void onFailure(Call call, IOException e) {
        handler.sendEmptyMessage(FALL);
      }

      @Override//請求成功回調(diào)
      public void onResponse(Call call, Response response) throws IOException {
        //得到從網(wǎng)上獲取資源,轉(zhuǎn)換成我們想要的類型
        byte[] Picture_bt = response.body().bytes();
        //通過handler更新UI
        Message message = handler.obtainMessage();
        message.obj = Picture_bt;
        message.what = SUCCESS;
        handler.sendMessage(message);

      }
    });
  }

  //當(dāng)按鈕點擊時,執(zhí)行使用OKhttp上傳圖片到服務(wù)器(http://blog.csdn.net/tangxl2008008/article/details/51777355)
  //注意:有時候上傳圖片失敗,是服務(wù)器規(guī)定還要上傳一個Key,如果開發(fā)中關(guān)于網(wǎng)絡(luò)這一塊出現(xiàn)問題,就多和面試官溝通溝通
  public void uploading(View view) {
    //圖片上傳接口地址
    String url = "https://cache.yisu.com/upload/information/20200623/125/120728.jpg");

    //創(chuàng)建RequestBody封裝參數(shù)
    RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
    //創(chuàng)建MultipartBody,給RequestBody進(jìn)行設(shè)置
    MultipartBody multipartBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("image", "big.jpg", fileBody)
        .build();
    //創(chuàng)建Request
    Request request = new Request.Builder()
        .url(url)
        .post(multipartBody)
        .build();

    //創(chuàng)建okhttp對象
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .build();

    //上傳完圖片,得到服務(wù)器反饋數(shù)據(jù)
    okHttpClient.newCall(request).enqueue(new Callback() {
      @Override
      public void onFailure(Call call, IOException e) {
        Log.e("ff", "uploadMultiFile() e=" + e);
      }

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


  }

}

activity_main.xml

<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context="com.sn.picture_okhttp.MainActivity">


  <Button
    android:id="@+id/button"
    android:onClick="Picture_okhttp_bt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="下載圖片"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="59dp"/>

  <Button
    android:text="上傳圖片"
    android:onClick="uploading"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button2"
    android:layout_alignParentTop="true"
    android:layout_alignLeft="@+id/button"
    android:layout_alignStart="@+id/button"/>

  <ImageView
    android:id="@+id/imageView_okhttp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"/>

</RelativeLayout>

build.gradle //依賴

implementation 'com.squareup.okhttp3:okhttp:3.4.2'

關(guān)于怎么在Android中利用OkHttp實現(xiàn)一個圖片上傳下載功能問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI