日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

okhttp_utils的使用以及与服务端springboot交互中遇到的问题

發布時間:2025/3/11 编程问答 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 okhttp_utils的使用以及与服务端springboot交互中遇到的问题 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

okhttp_utils的使用以及與服務端springboot交互中遇到的問題

  • 1_okhttp_utils在Android studio中的引入方法
  • 2_okhttputils的使用舉例
  • 3_get和post的簡單使用
  • 3_圖片的上傳
    • 3.1_單張圖片的上傳
      • 3.1.1_獲取安卓本地圖片問題
      • 3.1.2_okhttputils上傳圖片代碼
      • 3.1.3_服務端接收圖片
    • 3.2_單張圖片帶參數上傳
  • 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.創建新activity項目“MyApplication”

package com.example.myapplication;import android.app.Application; import com.zhy.http.okhttp.OkHttpUtils; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient;public class MyApplication extends Application {@Overridepublic void onCreate(){super.onCreate();OkHttpClient okHttpClient = new OkHttpClient.Builder() // .addInterceptor(new LoggerInterceptor("TAG")).connectTimeout(10000L, TimeUnit.MILLISECONDS).readTimeout(10000L, TimeUnit.MILLISECONDS)//其他配置.build();OkHttpUtils.initClient(okHttpClient);} }

3.callBack函數可自己定義(用來獲取請求后服務端返回的數據)

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的使用舉例

下載實例代碼sampleOkhttp

3_get和post的簡單使用

主要是路徑url參數問題,對于post方法無需寫?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_獲取安卓本地圖片問題

獲取手機本地文件和電腦操作略有不同,由于每部手機路徑都可能不一樣,所以先使用函數getFilesDir()/getCacheDir()/getExternalFilesDir()/getExternalCacheDir()/StorageDirectory()獲取路徑,然后進行文件操作

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

獲取文件操作轉載

示例

Log.i("tag",Environment.getExternalStorageDirectory().toString());File file = new File(Environment.getExternalStorageDirectory()+"/Pictures", "dabai.jpg");//讀取getExternalStorageDirectory()路徑下Pictures文件夾下的圖片if (!file.exists()){Toast.makeText(MainActivity.this, "文件不存在,請修改文件路徑", Toast.LENGTH_SHORT).show();return;}

Log.i("tag",Environment.getExternalStorageDirectory().toString());輸出結果:

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)//可以寫多條語句上傳多張圖片.build()//.execute(new MyStringCallback());}

url是服務端路徑;
addFile(“pictureFile”,“xixi.jpg”, file)中的pictureFile是服務端的value名

3.1.3_服務端接收圖片

服務端接收圖片并不是File類型的,若寫成File會報錯,具體原因見MultipartFile與File詳解與相互轉換

服務端代碼:
Controller:

/*獲取圖片*/@RequestMapping(value = "getPicture",method = RequestMethod.POST)public void getPicture(@RequestParam(value = "pictureFile") MultipartFile multipartFile){System.out.println("收到");FileOperation.multipartfileToFile(multipartFile);return ;}

FileOperation:

public class FileOperation {static String multipartfileToFilePath = "C:\\Users\\Administrator\\Desktop\\wode\\最近有用"; /*將客戶端傳來的MultipartFile類型的圖片轉換為File并存儲到路徑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());// 輸出絕對路徑System.out.println(file.getAbsolutePath());bufferedReader.close();}catch (Exception e){System.out.println("FileOperationServer:"+e.toString());}} }

3.2_單張圖片帶參數上傳

客戶端:

/*帶參數上傳一張圖片*/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()//返回響應{@Overridepublic void onError(Call call, Exception e, int id) {}@Overridepublic void onResponse(String response, int id) {Log.i("tag",response);}});}

服務端:

@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";//通過UUID類(表示通用唯一標識符的類)獲得唯一值,UUID表示一個128位的值FileOperation.multipartfileToFile(multipartFile,pictureName);return new PointServer().savePoint(userId,longitude,latitude,text,pictureName);} }

其中FileOperation.multipartfileToFile(multipartFile,pictureName);用于存儲圖片

4_圖片的下載

客戶端:

/*下載圖片*/public void getPicture(){String url = "http://10.200.231.191:8081" + "/PointServer/image";OkHttpUtils.get().url(url).build().execute(new BitmapCallback()//服務器返回響應{@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上}});}

服務端:

@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;}

總結

以上是生活随笔為你收集整理的okhttp_utils的使用以及与服务端springboot交互中遇到的问题的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。