Android開發(fā)中利用Retrofit如何將圖文上傳到服務器?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
創(chuàng)新互聯(lián)專注于進賢網(wǎng)站建設服務及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗。 熱誠為您提供進賢營銷型網(wǎng)站建設,進賢網(wǎng)站制作、進賢網(wǎng)頁設計、進賢網(wǎng)站官網(wǎng)定制、小程序開發(fā)服務,打造進賢網(wǎng)絡公司原創(chuàng)品牌,更為您提供進賢網(wǎng)站排名全網(wǎng)營銷落地服務。
前言:現(xiàn)在大多數(shù)的項目中都涉及圖片+文字上傳了,下面請詳見實現(xiàn)原理:
開發(fā)環(huán)境:AndroidStudio
1.引入依賴:
compile 'com.squareup.retrofit2:retrofit:2.1.0'
2.網(wǎng)絡權限:
<uses-permission android:name="android.permission.INTERNET" />
3.創(chuàng)建上傳對象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)//設置讀取超時時間 .writeTimeout(10, TimeUnit.SECONDS)//設置寫的超時時間 .connectTimeout(15, TimeUnit.SECONDS)//設置連接超時時間 .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(); //構建Request請求 final Request request = new Request.Builder() .url(url)//地址 .post(body)//添加請求體 // .post(requestBody)//添加請求體 .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()僅可調用一次。否則報IllegalStateException: closed異常 Log.i("file1", "上傳照片成功-->" + data); onSuccess(listener, data); call.cancel();//上傳成功取消請求釋放內存 } } @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)絡不穩(wěn)定請求超時!"); } else { onError(listener, e.getMessage()); } call.cancel();//上傳失敗取消請求釋放內存 } }); }
//注意:添加手機圖片,別忘了添加SD卡權限
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)//設置讀取超時時間 .writeTimeout(10, TimeUnit.SECONDS)//設置寫的超時時間 .connectTimeout(15, TimeUnit.SECONDS)//設置連接超時時間 .build(); /** * 實例--》添加商品 */ 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(); //構建Request請求 final Request request = new Request.Builder() .url(url)//地址 .post(body)//添加請求體 // .post(requestBody)//添加請求體 .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()僅可調用一次。否則報IllegalStateException: closed異常 Log.i("file1", "上傳照片成功-->" + data); onSuccess(listener, data); call.cancel();//上傳成功取消請求釋放內存 } } @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)絡不穩(wěn)定請求超時!"); } else { onError(listener, e.getMessage()); } call.cancel();//上傳失敗取消請求釋放內存 } }); } 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)絡請求成功 void onSuccess(String data); //網(wǎng)絡請求失敗 void onFailure(String errorMassage); } }
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對創(chuàng)新互聯(lián)的支持。
網(wǎng)站名稱:Android開發(fā)中利用Retrofit如何將圖文上傳到服務器
當前網(wǎng)址:http://www.rwnh.cn/article36/gcggsg.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供微信小程序、動態(tài)網(wǎng)站、做網(wǎng)站、標簽優(yōu)化、品牌網(wǎng)站制作、品牌網(wǎng)站建設
聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)