Android中使用retrofit2进行网络get请求查询数据和post请求上传文件
場景
Retrofit2
Retrofit 是對(duì) OkHttp 的封裝,是主流的網(wǎng)絡(luò)框架。
適用于Android 和 Java 的類型安全的HTTP客戶端,由Square提供的。
Retrofit是一種HTTP客戶端框架,使用它,我們可以完成有關(guān)HTTP的工作。
Retrofit Github 主頁:
https://github.com/square/Retrofit
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
關(guān)注公眾號(hào)
霸道的程序猿
獲取編程相關(guān)電子書、教程推送與免費(fèi)下載。
實(shí)現(xiàn)
導(dǎo)入依賴
在build.gradle中添加依賴
??? //Retrofit(網(wǎng)絡(luò)請(qǐng)求框架)implementation 'com.squareup.retrofit2:retrofit:2.5.0'implementation 'com.squareup.retrofit2:converter-gson:2.5.0'添加位置
?
然后點(diǎn)擊右上角的Sync now
注意:這里不能導(dǎo)入OkHttp與Gson,Retrofit內(nèi)部已經(jīng)包含這兩個(gè)框架,否則會(huì)導(dǎo)致版本沖突。
打卡網(wǎng)絡(luò)權(quán)限
在AndroidManifest中添加網(wǎng)絡(luò)權(quán)限。
<uses-permission android:name="android.permission.INTERNET" />搭建Http客戶端
為了在調(diào)用接口時(shí)方便我們新建一個(gè)單例模式的類WebClient去構(gòu)造Retrofit的實(shí)例
在src下包路徑下新建web包,包下新建webclient類
package com.badao.badaoimclient.web;import android.util.Log;import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory;public class WebClient {private static ApiService INSTANCE;private static final String BASE_URL = "http://你的后臺(tái)服務(wù)的ip:8000/";public static ApiService getInstance() {if (INSTANCE == null) {synchronized (ApiService.class) {if (INSTANCE == null) {INSTANCE = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build().create(ApiService.class);Log.i("INSTANCE",BASE_URL);}}}return INSTANCE;}}這里指定的BASE_RUL就是你后臺(tái)服務(wù)地址的ip+端口號(hào),最后要帶一個(gè)斜杠。
然后客戶端需要返回一個(gè)接口類ApiService,這個(gè)接口類是自定義的。
新建接口類ApiService
package com.badao.badaoimclient.web;import com.badao.badaoimclient.bean.ImUserBean; import com.badao.badaoimclient.bean.UploadBean; import okhttp3.MultipartBody; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Multipart; import retrofit2.http.POST; import retrofit2.http.Part;public interface ApiService {/*無參GET請(qǐng)求 *///沒有數(shù)據(jù)就填 '.' 或者 '/'//獲取通訊錄接口@GET("system/imuser/listForApp")Call<ImUserBean> getImUserList();//文件上傳接口@Multipart@POST("/common/upload")Call<UploadBean> upload(@Part MultipartBody.Part file);}這里接口類中有兩個(gè)方法,一個(gè)是get方法請(qǐng)求數(shù)據(jù),一個(gè)是post方法上傳文件。
先看這里的get請(qǐng)求的接口,接口的返回值ImUserBean是根據(jù)服務(wù)接口返回的Json數(shù)據(jù)生成的bean。
?
怎樣根據(jù)Json數(shù)據(jù)生成實(shí)體Bean參考如下:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/110426851
生成的實(shí)體ImUserBean如下
package com.badao.badaoimclient.bean;import com.google.gson.annotations.SerializedName;import java.util.List;public class ImUserBean {private int total;private int code;private Object msg;private List<RowsBean> rows;public int getTotal() {return total;}public void setTotal(int total) {this.total = total;}public int getCode() {return code;}public void setCode(int code) {this.code = code;}public Object getMsg() {return msg;}public void setMsg(Object msg) {this.msg = msg;}public List<RowsBean> getRows() {return rows;}public void setRows(List<RowsBean> rows) {this.rows = rows;}public static class RowsBean {@SerializedName("id")private int idX;@SerializedName("imNum")private String imNumX;@SerializedName("canOnline")private int canOnlineX;public int getIdX() {return idX;}public void setIdX(int idX) {this.idX = idX;}public String getImNumX() {return imNumX;}public void setImNumX(String imNumX) {this.imNumX = imNumX;}public int getCanOnlineX() {return canOnlineX;}public void setCanOnlineX(int canOnlineX) {this.canOnlineX = canOnlineX;}} }然后真正調(diào)用的接口的url就是
上面配置的BASE_URL加上你的接口方法中配置的url
Get接口調(diào)用
在需要調(diào)用get接口請(qǐng)求數(shù)據(jù)的地方
??????? //異步請(qǐng)求通訊錄WebClient.getInstance().getImUserList().enqueue(new Callback<ImUserBean>() {@Overridepublic void onResponse(Call<ImUserBean> call, Response<ImUserBean> response) {Log.i("response",response.toString());if(response.code()==200) {//獲取請(qǐng)求的數(shù)據(jù)并進(jìn)行后續(xù)操作ImUserBean userBean = response.body();rowsBeanList = userBean.getRows();myAdapter = new MyAdapter(rowsBeanList);listView.setAdapter(myAdapter);}}@Overridepublic void onFailure(Call<ImUserBean> call, Throwable t) {Log.i("onFailure",t.toString());}});}通過它的回調(diào)方法來獲取響應(yīng)碼和響應(yīng)體。
此后臺(tái)接口是用SpringBoot寫成,后臺(tái)get接口部分實(shí)現(xiàn)
??? @GetMapping("/listForApp")@ResponseBodypublic TableDataInfo listGet(ImUser imUser){startPage();List<ImUser> list = imUserService.selectImUserList(imUser);return getDataTable(list);}其中在getDataTable中最終返回
?
調(diào)用一下此接口可以看到其響應(yīng)碼為200
?
響應(yīng)體就是上面的json數(shù)據(jù)
?
然后可以將get請(qǐng)求的數(shù)據(jù)通過適配器顯示在ListView上
?
關(guān)于適配器的使用參照如下:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/111240545
POST請(qǐng)求上傳文件?
首先在ApiService中添加接口聲明
??? //文件上傳接口@Multipart@POST("/common/upload")Call<UploadBean> upload(@Part MultipartBody.Part file);然后在需要用到進(jìn)行文件上傳的地方
??????????????? //上傳語音文件到服務(wù)器RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);WebClient.getInstance().upload(part).enqueue(new Callback<UploadBean>() {@Overridepublic void onResponse(Call<UploadBean> call, Response<UploadBean> response) {if(response.code()==200){//對(duì)服務(wù)器地址進(jìn)行賦值chatItem.setRemoteContent(response.body().getFileName());}else {Toast.makeText(App.context,"服務(wù)器返回"+response.code(),Toast.LENGTH_SHORT).show();return;}}@Overridepublic void onFailure(Call<UploadBean> call, Throwable t) {Toast.makeText(App.context,t.toString(),Toast.LENGTH_SHORT).show();}});其中file就是需要進(jìn)行上傳的文件,需要構(gòu)造出一個(gè)part對(duì)象,然后下面是兩個(gè)回調(diào)方法
觸發(fā)post方法后,構(gòu)造part對(duì)象成功
?
后臺(tái)使用sprinboot寫的post接口
??? /*** 通用上傳請(qǐng)求*/@PostMapping("/common/upload")@ResponseBodypublic AjaxResult uploadFile(MultipartFile file) throws Exception{try{// 上傳文件路徑String filePath = RuoYiConfig.getUploadPath();// 上傳并返回新文件名稱String fileName = FileUploadUtils.upload(filePath, file);String url = serverConfig.getUrl() + fileName;AjaxResult ajax = AjaxResult.success();ajax.put("fileName", fileName);ajax.put("url", url);return ajax;}catch (Exception e){return AjaxResult.error(e.getMessage());}}后臺(tái)接收到請(qǐng)求后
?
后臺(tái)返回給Android后
?
?
?
總結(jié)
以上是生活随笔為你收集整理的Android中使用retrofit2进行网络get请求查询数据和post请求上传文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AndroidStudio中提示:Did
- 下一篇: Android+Java中使用RSA加密