Android基于OkHttp實現(xiàn)下載和上傳圖片
本文實例為大家分享了OkHttp實現(xiàn)下載圖片和上傳圖片的具體代碼,供大家參考,具體內(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ò)成功,進行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://www.718shop.com/sell/sell.m.picture.upload.do";
//創(chuàng)建上傳文件對象
File file = new File(Environment.getExternalStorageDirectory(), "big.jpg");
//創(chuàng)建RequestBody封裝參數(shù)
RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
//創(chuàng)建MultipartBody,給RequestBody進行設(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'
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android自定義Drawable之在Drawable中部指定透明區(qū)域方法示例
對于不同的屏幕密度、不同的設(shè)備方向,不同的語言和區(qū)域,都會涉及到備選 drawable 資源,下面這篇文章主要給你大家介紹了關(guān)于Android自定義Drawable之在Drawable中部指定透明區(qū)域的相關(guān)資料,需要的朋友可以參考下2018-07-07
Android自定義View實現(xiàn)支付寶支付成功-極速get花式Path炫酷動畫
這篇文章主要介紹了Android自定義View實現(xiàn)支付寶支付成功-極速get花式Path炫酷動畫的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-01-01
Android編程之ProgressBar圓形進度條顏色設(shè)置方法
這篇文章主要介紹了Android編程之ProgressBar圓形進度條顏色設(shè)置方法,涉及ProgressBar布局及屬性設(shè)置相關(guān)操作技巧,需要的朋友可以參考下2017-02-02
Android Fragment動態(tài)創(chuàng)建詳解及示例代碼
這篇文章主要介紹了Android Fragment動態(tài)創(chuàng)建詳解的相關(guān)資料,并附實例代碼及實現(xiàn)效果圖,需要的朋友可以參考下2016-11-11
Android獲取本地相冊圖片和拍照獲取圖片的實現(xiàn)方法
這篇文章主要為大家詳細(xì)介紹了Android獲取本地相冊圖片和拍照獲取圖片的實現(xiàn)方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03
phonegap教程使用jspdf庫在應(yīng)用中生成pdf文件(pdf生成方法)
在PhoneGap應(yīng)用中生成pdf文件,實現(xiàn)起來很簡單,使用JSPDF這個標(biāo)準(zhǔn)的JavaScript類庫來實現(xiàn)這個功能2014-01-01
Android實現(xiàn)短信驗證碼獲取自動填寫功能(詳細(xì)版)
這篇文章主要為大家詳細(xì)介紹了Android實現(xiàn)短信驗證碼獲取自動填寫功能,很實用的功能分享給大家,感興趣的小伙伴們可以參考一下2016-08-08
android studio logcat 無篩選 顯示全部日志 無應(yīng)用包名區(qū)分方式
這篇文章主要介紹了android studio logcat 無篩選 顯示全部日志 無應(yīng)用包名區(qū)分方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04

