新手秒学OkHttp+Retrofit框架,适合新手
Retrofit简单的一句话就是通过通过代理方式和注解转换成一个serviceMethod然后调用callFactory执行的okhttp3.Callt得到返回的数据serviceMethod.callAdapter.adapt(okHttpCall)来产生method所定义的返回值
下一章实现Retrofit+RxJava+OkHttp
这章我们来简单实现OkHttp+Retrofit
1、添加依赖库
//OkHttp库 implementation 'com.squareup.okhttp3:okhttp:3.4.1' //retrofit库 implementation 'com.squareup.retrofit2:retrofit:2.1.0'
2、第二步创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder().baseUrl("你的服务器地址").build();//
http://127.0.0.1:8080/Canteen/
3、创建请求接口
GetRequest_Interfaces getRequest_interfaces = retrofit.create(GetRequest_Interfaces.class);
这个接口是一个自定义的,名字随便你取,接口的具体内容如下,里面采用了post请求与get请求,其中map代表了参数键值对
public interface GetRequest_Interfaces { /** * 登录,使用get方式 * @return */ @GET("userLogin") Call<ResponseBody> doGetLogin(@FieldMap Map<String, String> params); /** * 登录,使用Post方式 * @return */ @POST("userLogin") @FormUrlEncoded//表示请求体是一个form表单 Call<ResponseBody> doPostLogin( @FieldMap Map<String, String> params); }
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任何配置缓存的,适合新手看,后续有时间再写写复杂的