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