android Retrofit+RXJAVA

1、添加依赖

//only Retrofit(只用Retrofit联网)
    implementation 'com.squareup.retrofit2:retrofit:2.1.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
//Rxjava and Retrofit(Retrofit+Rx需要添加的依赖)
    implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
    implementation 'io.reactivex:rxandroid:1.2.1'
    implementation 'io.reactivex:rxjava:1.2.1'

2、实例,上传文件
①接口

   public interface HttpRequestURL {
        @Multipart
        @POST(".") //无参数加“.”(点)
        Observable<UploadBean> postImgUpload(@Part MultipartBody.Part file);
    }

②实现UploadBean 需要返回数据的实体类

MultipartBody.Part part = FromURLUploadIpml.getMultipartBody(tmp.getFilename());
        //一般参数
        //  images.put("visit_type", RequestBody.create(MediaType.parse("text/html; charset=utf-8"), "canshu"));
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)//基础URL 建议以 / 结尾
                .addConverterFactory(GsonConverterFactory.create())//设置 Json 转换器
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//RxJava 适配器
                .build();
        HttpRequestURL fromURLUpload = retrofit.create(HttpRequestURL.class);
        fromURLUpload.postImgUpload(part)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<UploadBean>() {
                    @Override
                    public void onCompleted() {
                        Log.i("fenxi", "onCompleted");
                    }
                @Override
                public void onError(Throwable e) {
                    Log.i("fenxi", "onError:"+ e.getMessage());
                }
                @Override
                public void onNext(UploadBean uploadBean) {
                    Log.i("fenxi", "上传成功"); 
            });

public static MultipartBody.Part getMultipartBody(String filename) {
        File file =null;
        File files =null;
        RequestBody requestBody =null;
        try {
        String path = "/sdcard/golding/pics/";
        file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        String filepath = path  + filename;
        files = new File(filepath);
        Log.i("fenxi", "upload File size:"+files.length());
        //attach_file
            requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), files);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  MultipartBody.Part.createFormData("file", files.getName(), requestBody);
    }

3、注解和删除

请求方法类注解
@GET
GET网络请求方式,通常后面括号要子接口地址
例如提交一个无参数的get请求:
//接口:http://www.weather.com.cn/data/sk/101010100.html
@GET("data/sk/101010100.html")
Call <Weather> getWeather();

@PSOT
POST网络请求方式
@PUT
@DELETE
@PATCH
@HEAD
@OPTIONS
@HTTP
以上为不常用请求方式,这里不做解释
参数类注解
@Headers
头信息参数
@Path
路径参数,用于替换url路径中的变量字符替换,也就是url中的{}中的部分
(@Path主要用于Get请求)
例如接口:子连接地址中/wages/{wageId}/detail
替换部分:{wageId}中的wageId.
@GET("wages/{wageId}/detail") 
Call<VideoInfo >getVideoData(@Path("wageId") String wageId);

@Query
形成单个查询参数,将接口url中追加类似于"page=1"的字符串,形成提交给服务器端的参数,
主要用于Get请求数据,用于拼接在拼接在url路径后面的查询参数,一个@Query相当于拼接一个参数
下例中:
形成提交参数的部分:name=aaa
//http://www.baidu.com/?name=aaa
@GET("jp/avlist/202861101/1/") 
Call VideoInfo getVideoData(@Query("name") String name);

多个参数中间用,隔开
下例中形成提交参数的部分:type=yuantong&postid=500379523313
//接口:http://www.kuaidi100.com/query?type=yuantong&postid=500379523313"
@GET("query") 
Call QueryInfo QueryInfo(@Query("type") String type,@Query("postid") String postid);

@QueryMap
查询参数集合,将url中追加类似于"page=1&count=20"的字符串,形成提交给服务器端的参数.
效果等同于多个@Query参数拼接,主要用于Get请求网络数据
例如接口:
http://www.kuaidi100.com/query?type=yuantong&postid=500379523313"
形成提交参数的部分:
ype=yuantong&postid=500379523313
Call QueryInfo QueryInfo(@QueryMap Map<String, String> map) ;

@Url
使用此注解参数后,@GET后无需在添加任何内容.
方法中的@Url参数可以是全路径参数,也可以是子路径参数,但是baseurl必须要指定.
@Field
指定form表单中域中每个控件name以及相应数值
@Field的用法类似于@Query,不同的是@Field主要用于Post请求
@FieldMap
表单域集合
用于Post请求数据,@FieldMap的用法类似于@QueryMap
@Part
Post提交分块请求
(表单字段,与 PartMap 配合,适合文件上传情况)
@PartMap
表单字段,与 Part 配合,适合文件上传情况;默认接受 Map<String, RequestBody> 类型,非 RequestBody 会通过 Converter 转换
@Body
(指定一个对象作为 request body)非表单请求体
@POST("users/new")
Call<User> createUser(@Body User user);

标记类注解:
@FormUrlEncoded
对表单域中填写的内容进行编码处理,避免乱码.
(用于post请求.)
例如:
@FormUrlEncoded
@POST(“/user/edit”)
Call updateUnableApeName(@Field(“first_name”) String first,
        @Field(“last_name”) String last);

@MultiPart
Post提交分块请求,如果上传文件必须指定MultiPart
(请求体是支持文件上传的 From 表单)
@Streaming
响应体的数据用流的形式返回
(未使用该注解,默认会把数据全部载入内存,之后通过流读取内存中数据,所以返回数据较大时,需要使用该注解)

猜你喜欢

转载自blog.csdn.net/u012901807/article/details/86637209