码迷,mamicode.com
首页 > Web开发 > 详细

okhttp进行网络传输文件

时间:2018-03-20 15:53:55      阅读:530      评论:0      收藏:0      [点我收藏+]

标签:new   service   coding   callback   网络   ack   gre   pex   creat   

其中使用了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);

 

okhttp进行网络传输文件

标签:new   service   coding   callback   网络   ack   gre   pex   creat   

原文地址:https://www.cnblogs.com/zl1991/p/8609611.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!