okhttp进行网络传输文件
其中使用了RXJava。
1 public class HttpDataManager { 2 3 private static HttpDataManager INSTANCE; 4 private RequestService service; 5 private static String ONLINE_URL = "http://baidu.com/"; 6 7 public static HttpDataManager getInstance() { 8 if (INSTANCE == null) { 9 INSTANCE = new HttpDataManager(); 10 } 11 return INSTANCE; 12 } 13 14 public HttpDataManager() { 15 this.service = createService(); 16 } 17 18 private RequestService createService() { 19 OkHttpClient client = new OkHttpClient.Builder() 20 .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC)) 21 .build(); 22 Retrofit retrofit = new Retrofit.Builder() 23 .client(client) 24 .baseUrl(ONLINE_URL) 25 .addConverterFactory(ResponseConvertFactory.create()) 26 .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) 27 .build(); 28 return retrofit.create(RequestService.class); 29 } 30 31 public RequestService getService() { 32 return service; 33 } 34 }
1 public interface RequestService { 2 3 /** 4 * getOcrRecog 5 * @return 6 */ 7 @Multipart 8 @POST("reventondc/v5/ocr/json") 9 Observable<OcrRecogResult> getOcrRecog(@Part MultipartBody.Part file); 10 }
1 public class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> { 2 3 private final Gson gson; 4 private final Type type; 5 6 GsonResponseBodyConverter(Gson gson, Type type) { 7 this.gson = gson; 8 this.type = type; 9 } 10 11 @Override 12 public T convert(ResponseBody value) throws IOException { 13 String response = value.string(); 14 checkError(response); 15 16 return gson.fromJson(response, type); 17 } 18 19 20 public void checkError(String response) throws MyHttpException { 21 try { 22 JSONObject rawResponeJson = new JSONObject(response); 23 int code = 200; 24 String msg = ""; 25 if (rawResponeJson.has("code")) { 26 code = rawResponeJson.getInt("code"); 27 } 28 if (rawResponeJson.has("message")) { 29 msg = rawResponeJson.getString("message"); 30 } 31 if (code != 200) { 32 throw new MyHttpException(code, msg); 33 } 34 } catch (JSONException e) { 35 e.printStackTrace(); 36 } 37 } 38 }
1 public class ResponseConvertFactory extends Converter.Factory { 2 3 4 /** 5 * Create an instance using a default {@link Gson} instance for conversion. Encoding to JSON and 6 * decoding from JSON (when no charset is specified by a header) will use UTF-8. 7 */ 8 public static ResponseConvertFactory create() { 9 return create(new Gson()); 10 } 11 12 /** 13 * Create an instance using {@code gson} for conversion. Encoding to JSON and 14 * decoding from JSON (when no charset is specified by a header) will use UTF-8. 15 */ 16 public static ResponseConvertFactory create(Gson gson) { 17 return new ResponseConvertFactory(gson); 18 } 19 20 private final Gson gson; 21 22 private ResponseConvertFactory(Gson gson) { 23 if (gson == null) { 24 throw new NullPointerException("gson == null"); 25 } 26 this.gson = gson; 27 } 28 29 @Override 30 public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, 31 Retrofit retrofit) { 32 return new GsonResponseBodyConverter<>(gson,type); 33 } 34 }
1 public class MyHttpException extends RuntimeException { 2 3 public int code; 4 public String msg; 5 6 public MyHttpException(int code, String msg){ 7 super(msg); 8 this.code = code; 9 this.msg = msg; 10 } 11 12 }
调用方式:
1 mOcrConsumer = new Consumer<OcrRecogResult>() { 2 3 @Override 4 public void accept(OcrRecogResult ocrRecogResult) throws Exception { 5 if (mCallBack != null) { 6 mCallBack.success(ocrRecogResult); 7 } 8 } 9 }; 10 11 mThrowableConsumer = new Consumer<Throwable>() { 12 @Override 13 public void accept(Throwable throwable) throws Exception { 14 if (mCallBack != null) { 15 mCallBack.fail(throwable.getMessage()); 16 } 17 } 18 };
传输本地图片文件:
1 File file = new File(filepath); 2 3 RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file); 4 MultipartBody.Part body = MultipartBody.Part.createFormData("pic", file.getName(), requestFile); 5 6 HttpDataManager.getInstance().getService().getOcrRecog(body).subscribeOn(Schedulers.io()) 7 .subscribe(mOcrConsumer, mThrowableConsumer);
传输内存图片:
1 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 2 bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream); 3 4 RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), byteArrayOutputStream.toByteArray()); 5 MultipartBody.Part body = MultipartBody.Part.createFormData("pic", "src.jpg", requestFile); 6 7 HttpDataManager.getInstance().getService().getOcrRecog(body).subscribeOn(Schedulers.io()) 8 .subscribe(mOcrConsumer, mThrowableConsumer);
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了