新手秒学OkHttp Retrofit框架,适合新手

 

项目地址GitHub项目地址(Kotlin版组件化)

 

Retrofit简单的一句话就是通过通过代理方式和注解转换成一个serviceMethod然后调用callFactory执行的okhttp3.Callt得到返回的数据serviceMethod.callAdapter.adapt(okHttpCall)来产生method所定义的返回值

下一章实现Retrofit+RxJava+OkHttp

这章我们来简单实现OkHttp+Retrofit

1、添加依赖库

 

implementation 'com.squareup.okhttp3:okhttp:3.4.1'//OkHttp库
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'//gson库
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'//retrofit库
    implementation 'com.squareup.retrofit2:adapter-rxjava:2.3.0'//rxjava库
    implementation 'io.reactivex:rxandroid:1.2.1'//rxandroid库

2、第二步创建Retrofit对象 

//设置OkHttpClient超时配置

int CONNECT_TIMEOUT = 10;
int READ_TIMEOUT = 20;
int WRITE_TIMEOUT = 20;
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newBuilder().connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS); // 连接超时时间阈值
okHttpClient.newBuilder().readTimeout(READ_TIMEOUT, TimeUnit.SECONDS);  // 数据获取时间阈值
okHttpClient.newBuilder().writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS);// 写数据超时时间阈值
//创建Retrofit
retrofit = new Retrofit.Builder()
        .baseUrl(url)
        .addConverterFactory(GsonConverterFactory.create()) // 设置数据解析器
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())// 支持RxJava平台
        .client(okHttpClient)//载入Okhttp
        .build();//创建

3、创建请求接口

public interface GetRequest_Interfaces {
//GET请求,参数连接
@GET("login?uphone=2&upassword=2")
Call<User> login();

//GET请求,参数连接自定义参数
@GET("login")
Call<User> login(@Query("uphone") String uphone,@Qunery("upassword") String upassword);

//GET请求,Map键值对
@GET("login")
Call<User> login(@QueryMap uphone);

//GET请求,Path形式
@GET("loginget/{uphone}")
Call<User> loginUphone(@Path("uphone") String uphone);


//POST请求,Map键值对形式,跟@FormUrlEncoded结合使用
@POST("loginpost")
@FormUrlEncoded//表示请求体是一个form表单
Call<User> doPostLogin(@FieldMap Map<String, String> params);

//POST请求,单个参数形式,跟@FormUrlEncoded结合使用
@POST("loginpost")
@FormUrlEncoded
Call<User> getLoginPost(@Field("uphone") String uphone, @Field("upassword") String upassword);

//POST请求,文件上传,跟@Multipartd结合使用
    @POST("register")
    @Multipart
    Call<User> Regiseter(@PartMap Map<String, RequestBody> map, @Part MultipartBody.Part file);

//POST请求,多文件上传,跟@FormUrlEncoded结合使用
    @POST("register")
    @Multipart
    Call<User> RegiseterMore(@PartMap Map<String, RequestBody> map, @Part MultipartBody.Part[] file);

//DELETE请求,删除,Path形式
@DELETE("logindelete/{uphone}")
Call<User> getLoginDelete(@Path("uphone") String uphone);

//PUT请求,Part/PartMap形式,跟@Multipart结合使用
@PUT("loginput")
@Multipart
Call<User> getLoginPut(@Part("uphone") String uphone, @Part("upassword") String upassword);


//POST请求,文件上传,跟@Multipartd结合使用的参数封装;多文件就用数组循环封装多个就行了
/* //封装文件
        RequestBody requestBody =
                RequestBody.create(MediaType.parse("application/otcet-stream"), imageFile);
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("imageFile", imageFile.getName(), requestBody);
        //封装参数
        Map<String,RequestBody> map = new HashMap<>();
        map.put("uphone",RequestBody.create(null,"18682026498"));
        map.put("upassword",RequestBody.create(null,"123456"));
        map.put("uname",RequestBody.create(null,"张三"));*/

//@Body上传 JSON格式(需要将基类对象转换成JSONOBJect)
@POST("xxxxxxx")   
Call<Object> login( @Body JSONObject parmas );  

//@Body上传 JSON格式(需要将基类对象转换成JSONOBJect)再将JSON转换成RequestBody上传
@POST("xxxxxxx")   
Call<Object> login( @Body RequestBodyparmas );  


}
GetRequest_Interfaces getRequest_interfaces = retrofit.create(GetRequest_Interfaces.class);

  这个接口是一个自定义的,名字随便你取,接口的具体内容如下,里面采用了post请求与get请求,其中map代表了参数键值对

4、将封装好的参数放入自定义接口中
Call<ResponseBody> call = getRequest_interfaces.doPostLogin(params);
5、执行
call.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {

    }
});

这篇文章是不做Retrofit任何配置缓存的,适合新手看,后续有时间再写写复杂的

感谢:https://blog.csdn.net/carson_ho/article/details/73732076

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值