Android基於OkHttp實現下載和上傳圖片

這篇文章主要爲大家詳細介紹了Android基於OkHttp實現下載和上傳圖片功能,具有一定的參考價值,感興趣的小夥伴們可以參考一下

本文實例爲大家分享了OkHttp實現下載圖片和上傳圖片的具體代碼,供大家參考,具體內容如下

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) {
        //加載網絡成功,進行UI的更新,處理得到的圖片資源
        case SUCCESS:
          //通過message,拿到字節數組
          byte[] Picture = (byte[]) msg.obj;
          //使用BitmapFactory工廠,把字節數組轉換爲bitmap
          Bitmap bitmap = BitmapFactory.decodeByteArray(Picture, 0, Picture.length);
          //通過ImageView,設置圖片
          mImageView_okhttp.setImageBitmap(bitmap);
          break;
        //當加載網絡失敗,執行的邏輯代碼
        case FALL:
          Toast.makeText(MainActivity.this, "網絡異常", 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);
  }

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

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

      }
    });
  }

  //當按鈕點擊時,執行使用OKhttp上傳圖片到服務器(http://blog.csdn.net/tangxl2008008/article/details/51777355)
  //注意:有時候上傳圖片失敗,是服務器規定還要上傳一個Key,如果開發中關於網絡這一塊出現問題,就多和面試官溝通溝通
  public void uploading(View view) {
    //圖片上傳接口地址
    String url = "https://www.718shop.com/sell/sell.m.picture.upload.do";
    //創建上傳文件對象
    File file = new File(Environment.getExternalStorageDirectory(), "big.jpg");

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

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

    //上傳完圖片,得到服務器反饋數據
    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'

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章