国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

Retrofit實(shí)現(xiàn)圖文上傳至服務(wù)器

2019-11-09 16:33:35
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

前言:現(xiàn)在大多數(shù)的項(xiàng)目中都涉及圖片+文字上傳了,下面請(qǐng)?jiān)斠妼?shí)現(xiàn)原理:

開發(fā)環(huán)境:AndroidStudio

1.引入依賴

  compile 'com.squareup.retrofit2:retrofit:2.1.0'

2.網(wǎng)絡(luò)權(quán)限

<uses-permission android:name="android.permission.INTERNET" />

3.創(chuàng)建上傳對(duì)象OkHttpClient

PRivate static final OkHttpClient client = new OkHttpClient.Builder()            .addInterceptor(new Interceptor() {                @Override                public Response intercept(Chain chain) throws IOException {                    Request request = chain                            .request()                            .newBuilder()                            .build();                    return chain.proceed(request);                }            })            .readTimeout(10, TimeUnit.SECONDS)//設(shè)置讀取超時(shí)時(shí)間            .writeTimeout(10, TimeUnit.SECONDS)//設(shè)置寫的超時(shí)時(shí)間            .connectTimeout(15, TimeUnit.SECONDS)//設(shè)置連接超時(shí)時(shí)間            .build();

4.上傳圖片的公有方法

    private synchronized final static void uploadImgAndParameter(Map<String, Object> map, String url,                                                                 final UIDataListener listener) {        // mImgUrls為存放圖片的url集合        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);        if (null != map) {            for (Map.Entry<String, Object> entry : map.entrySet()) {                if (entry.getValue() != null) {                    if (entry.getValue() instanceof File) {                        File f = (File) entry.getValue();                        builder.addFormDataPart(entry.getKey(), f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));                    } else {                        builder.addFormDataPart(entry.getKey(), entry.getValue().toString());                    }                }            }        }        //創(chuàng)建RequestBody        RequestBody body = builder.build();//        MultipartBody requestBody = builder.build();        //構(gòu)建Request請(qǐng)求        final Request request = new Request.Builder()                .url(url)//地址                .post(body)//添加請(qǐng)求體//                .post(requestBody)//添加請(qǐng)求體                .build();        client.newCall(request).enqueue(new okhttp3.Callback() {            @Override            public void onResponse(Call call, final Response response) throws IOException {                if (response.isSuccessful()) {//判斷是否成功                    final String data = response.body().string();//string()僅可調(diào)用一次。否則報(bào)IllegalStateException: closed異常                    Log.i("file1", "上傳照片成功-->" + data);                    onSuccess(listener, data);                    call.cancel();//上傳成功取消請(qǐng)求釋放內(nèi)存                }            }            @Override            public void onFailure(Call call, final IOException e) {                Log.i("file2", "上傳失敗-->" + e.getMessage());                String msg = e.getMessage();                if (msg == null || msg.equals("timeout")) {                    onError(listener, "網(wǎng)絡(luò)不穩(wěn)定請(qǐng)求超時(shí)!");                } else {                    onError(listener, e.getMessage());                }                call.cancel();//上傳失敗取消請(qǐng)求釋放內(nèi)存            }        });    }//注意:添加手機(jī)圖片,別忘了添加SD卡權(quán)限

5.全部代碼:

public class HttpUtil {    private static final Handler handler = new Handler(Looper.getMainLooper());    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/*");    private static final OkHttpClient client = new OkHttpClient.Builder()            .addInterceptor(new Interceptor() {                @Override                public Response intercept(Chain chain) throws IOException {                    Request request = chain                            .request()                            .newBuilder()                            .build();                    return chain.proceed(request);                }            })            .readTimeout(10, TimeUnit.SECONDS)//設(shè)置讀取超時(shí)時(shí)間            .writeTimeout(10, TimeUnit.SECONDS)//設(shè)置寫的超時(shí)時(shí)間            .connectTimeout(15, TimeUnit.SECONDS)//設(shè)置連接超時(shí)時(shí)間            .build();    /**     * 實(shí)例--》添加商品     */    public static void addCoupon( int shopperId,String shopperName,                                 File file, final UIDataListener listener) {        String url = "shopappajx/shopAppCouponAction_saveCoupon.htm";        Map<String, Object> map = new HashMap<>();        map.put("shopperId", shopperId);        map.put("shopperName", shopperName);        map.put("couponImage", file);//商品圖片        uploadImgAndParameter(map, url, listener);    }    //上傳圖片共有方法    private synchronized final static void uploadImgAndParameter(Map<String, Object> map, String url,                                                                 final UIDataListener listener) {        // mImgUrls為存放圖片的url集合        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);        if (null != map) {            for (Map.Entry<String, Object> entry : map.entrySet()) {                if (entry.getValue() != null) {                    if (entry.getValue() instanceof File) {                        File f = (File) entry.getValue();                        builder.addFormDataPart(entry.getKey(), f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));                    } else {                        builder.addFormDataPart(entry.getKey(), entry.getValue().toString());                    }                }            }        }        //創(chuàng)建RequestBody        RequestBody body = builder.build();//        MultipartBody requestBody = builder.build();        //構(gòu)建Request請(qǐng)求        final Request request = new Request.Builder()                .url(url)//地址                .post(body)//添加請(qǐng)求體//                .post(requestBody)//添加請(qǐng)求體                .build();        client.newCall(request).enqueue(new okhttp3.Callback() {            @Override            public void onResponse(Call call, final Response response) throws IOException {                if (response.isSuccessful()) {//判斷是否成功                    final String data = response.body().string();//string()僅可調(diào)用一次。否則報(bào)IllegalStateException: closed異常                    Log.i("file1", "上傳照片成功-->" + data);                    onSuccess(listener, data);                    call.cancel();//上傳成功取消請(qǐng)求釋放內(nèi)存                }            }            @Override            public void onFailure(Call call, final IOException e) {                Log.i("file2", "上傳失敗-->" + e.getMessage());                String msg = e.getMessage();                if (msg == null || msg.equals("timeout")) {                    onError(listener, "網(wǎng)絡(luò)不穩(wěn)定請(qǐng)求超時(shí)!");                } else {                    onError(listener, e.getMessage());                }                call.cancel();//上傳失敗取消請(qǐng)求釋放內(nèi)存            }        });    }    private final static void onSuccess(final UIDataListener listener, final String data) {        handler.post(new Runnable() {            public void run() {                // 需要在主線程的操作。                listener.onSuccess(data);            }        });    }    private final static void onError(final UIDataListener listener, final String msg) {        if (null != listener) {            handler.post(new Runnable() {                public void run() {                    // 需要在主線程的操作。                    listener.onFailure(msg);                }            });        }    }    public interface UIDataListener {     //網(wǎng)絡(luò)請(qǐng)求成功        void onSuccess(String data);      //網(wǎng)絡(luò)請(qǐng)求失敗        void onFailure(String errorMassage);    }}


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 韩城市| 抚顺县| 博客| 琼中| 德江县| 上栗县| 汕头市| 泰宁县| 泽普县| 红桥区| 金昌市| 丹江口市| 凤山市| 大方县| 凌海市| 巴南区| 永和县| 永登县| 武安市| 墨江| 海盐县| 波密县| 格尔木市| 东光县| 鹤庆县| 庆城县| 武隆县| 勐海县| 沽源县| 吐鲁番市| 鲁甸县| 固原市| 昌吉市| 盐山县| 左权县| 论坛| 凌海市| 平阴县| 环江| 临潭县| 历史|