okhttp_utils的使用以及与服务端springboot交互中遇到的问题
okhttp_utils的使用以及與服務(wù)端springboot交互中遇到的問題
- 1_okhttp_utils在Android studio中的引入方法
- 2_okhttputils的使用舉例
- 3_get和post的簡(jiǎn)單使用
- 3_圖片的上傳
- 3.1_單張圖片的上傳
- 3.1.1_獲取安卓本地圖片問題
- 3.1.2_okhttputils上傳圖片代碼
- 3.1.3_服務(wù)端接收?qǐng)D片
- 3.2_單張圖片帶參數(shù)上傳
- 4_圖片的下載
1_okhttp_utils在Android studio中的引入方法
1.在app目錄下的build.gradle中添加
// 添加OKHttp支持implementation("com.squareup.okhttp3:okhttp:4.3.1")implementation 'com.zhy:okhttputils:2.6.2'
2.創(chuàng)建新activity項(xiàng)目“MyApplication”
3.callBack函數(shù)可自己定義(用來(lái)獲取請(qǐng)求后服務(wù)端返回的數(shù)據(jù))
public class MyStringCallback extends StringCallback{@Overridepublic void onBefore(Request request, int id){setTitle("loading...");}@Overridepublic void onAfter(int id){setTitle("Sample-okHttp");}@Overridepublic void onError(Call call, Exception e, int id){e.printStackTrace();Log.i("onError:",e.getMessage());}@Overridepublic void onResponse(String response, int id){Log.e(TAG, "onResponse:complete");Log.i("onResponse:",response);switch (id){case 100:Toast.makeText(MainActivity.this, "http", Toast.LENGTH_SHORT).show();break;case 101:Toast.makeText(MainActivity.this, "https", Toast.LENGTH_SHORT).show();break;}}}2_okhttputils的使用舉例
下載實(shí)例代碼sampleOkhttp
3_get和post的簡(jiǎn)單使用
主要是路徑url參數(shù)問題,對(duì)于post方法無(wú)需寫?account=…&password=…
/*get方法登錄*/public void loginGet(final String account, final String password){String url = "http://10.200.231.191:8081"+"/UserServer/loginByAccount?account="+account+"&password="+password;OkHttpUtils.get().url(url).build().execute(new StringCallback(){@Overridepublic void onError(Call call, Exception e, int id) {}@Overridepublic void onResponse(String response, int id) {Log.i("tag",response);}});}/*post方法登錄*/public void loginPost(final String account, final String password){String url = "http://10.200.231.191:8081"+"/UserServer/loginByAccount";OkHttpUtils.post().url(url).addParams("account", account).addParams("password", password).build().execute(new StringCallback(){@Overridepublic void onError(Call call, Exception e, int id) {}@Overridepublic void onResponse(String response, int id) {Log.i("tag",response);}});}3_圖片的上傳
3.1_單張圖片的上傳
3.1.1_獲取安卓本地圖片問題
獲取手機(jī)本地文件和電腦操作略有不同,由于每部手機(jī)路徑都可能不一樣,所以先使用函數(shù)getFilesDir()/getCacheDir()/getExternalFilesDir()/getExternalCacheDir()/StorageDirectory()獲取路徑,然后進(jìn)行文件操作
com.example.fang.test E/getFilesDir(): /data/user/0/com.example.fang.test/files/aa com.example.fang.test E/getCacheDir(): /data/user/0/com.example.fang.test/cache/aa com.example.fang.test E/getExternalFilesDir(): /storage/emulated/0/Android/data/com.example.fang.test/files/aa com.example.fang.test E/getExternalCacheDir(): /storage/emulated/0/Android/data/com.example.fang.test/cache/aa com.example.fang.test E/StorageDirectory(): /storage/emulated/0/aa獲取文件操作轉(zhuǎn)載
示例:
Log.i("tag",Environment.getExternalStorageDirectory().toString());File file = new File(Environment.getExternalStorageDirectory()+"/Pictures", "dabai.jpg");//讀取getExternalStorageDirectory()路徑下Pictures文件夾下的圖片if (!file.exists()){Toast.makeText(MainActivity.this, "文件不存在,請(qǐng)修改文件路徑", Toast.LENGTH_SHORT).show();return;}Log.i("tag",Environment.getExternalStorageDirectory().toString());輸出結(jié)果:
3.1.2_okhttputils上傳圖片代碼
public void convertPicture(File file) {String url = "http://10.200.231.191:8081" + "/UserServer/getPicture";Map<String, String> headers = new HashMap<>();OkHttpUtils.post()//.url(url)//.addFile("pictureFile","xixi.jpg", file)//可以寫多條語(yǔ)句上傳多張圖片.build()//.execute(new MyStringCallback());}url是服務(wù)端路徑;
addFile(“pictureFile”,“xixi.jpg”, file)中的pictureFile是服務(wù)端的value名
3.1.3_服務(wù)端接收?qǐng)D片
服務(wù)端接收?qǐng)D片并不是File類型的,若寫成File會(huì)報(bào)錯(cuò),具體原因見MultipartFile與File詳解與相互轉(zhuǎn)換
服務(wù)端代碼:
Controller:
FileOperation:
public class FileOperation {static String multipartfileToFilePath = "C:\\Users\\Administrator\\Desktop\\wode\\最近有用"; /*將客戶端傳來(lái)的MultipartFile類型的圖片轉(zhuǎn)換為File并存儲(chǔ)到路徑multipartfileToFilePath*/public static void multipartfileToFile(MultipartFile multipartFile){try{File file = new File(multipartfileToFilePath,"demo.jpg");multipartFile.transferTo(file);// 讀取文件第一行BufferedReader bufferedReader = new BufferedReader(new FileReader(file));System.out.println(bufferedReader.readLine());// 輸出絕對(duì)路徑System.out.println(file.getAbsolutePath());bufferedReader.close();}catch (Exception e){System.out.println("FileOperationServer:"+e.toString());}} }3.2_單張圖片帶參數(shù)上傳
客戶端:
/*帶參數(shù)上傳一張圖片*/public void convertPictureAndParam(int userId,float longitude,float latitude,String text,File file) {String url = "http://10.200.231.191:8081" + "/PointServer/savePoint";Map<String, String> headers = new HashMap<>();OkHttpUtils.post()//.url(url)//.addParams("userId",Integer.toString(userId)).addParams("longitude",Float.toString(longitude)).addParams("latitude",Float.toString(latitude)).addParams("text",text).addFile("pictureFile","xixi.jpg", file).build()//.execute(new StringCallback()//返回響應(yīng){@Overridepublic void onError(Call call, Exception e, int id) {}@Overridepublic void onResponse(String response, int id) {Log.i("tag",response);}});}服務(wù)端:
@RestController @RequestMapping("PointServer") public class PointController {@RequestMapping(value = "savePoint",method = RequestMethod.POST)public int savePoint(@RequestParam(value = "userId") int userId,@RequestParam(value = "longitude") float longitude,@RequestParam(value = "latitude") float latitude,@RequestParam(value = "text") String text,@RequestParam(value = "pictureFile")MultipartFile multipartFile){String pictureName = UUID.randomUUID().toString()+".jpg";//通過(guò)UUID類(表示通用唯一標(biāo)識(shí)符的類)獲得唯一值,UUID表示一個(gè)128位的值FileOperation.multipartfileToFile(multipartFile,pictureName);return new PointServer().savePoint(userId,longitude,latitude,text,pictureName);} }其中FileOperation.multipartfileToFile(multipartFile,pictureName);用于存儲(chǔ)圖片
4_圖片的下載
客戶端:
/*下載圖片*/public void getPicture(){String url = "http://10.200.231.191:8081" + "/PointServer/image";OkHttpUtils.get().url(url).build().execute(new BitmapCallback()//服務(wù)器返回響應(yīng){@Overridepublic void onError(Call call, Exception e, int id) {}@Overridepublic void onResponse(Bitmap response, int id) {Log.i("picture",response.getClass().toString());mImageView.setImageBitmap(response);//顯示在控件mImageView上}});}服務(wù)端:
@GetMapping(value = "image",produces = MediaType.IMAGE_JPEG_VALUE)@ResponseBodypublic byte[] test() throws Exception {File file = new File(FileOperation.readPicturePath,"4d5c3e33-67c2-4e66-9939-e97a3f49c36f.jpg");FileInputStream inputStream = new FileInputStream(file);byte[] bytes = new byte[inputStream.available()];inputStream.read(bytes, 0, inputStream.available());return bytes;}總結(jié)
以上是生活随笔為你收集整理的okhttp_utils的使用以及与服务端springboot交互中遇到的问题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机等级考试二级ACCESS考试大纲
- 下一篇: js对象的定义方法