Android 网络框架--Retrofit

1、导入Jar包

  compile 'com.google.code.gson:gson:2.8.0'

  compile 'com.squareup.retrofit2:retrofit:2.1.0'

  compile 'com.squareup.okhttp3:okhttp:3.4.2'

  compile 'com.squareup.retrofit2:converter-gson:2.1.0'

  compile 'com.squareup.retrofit2:converter-scalars:2.1.0'


2、创建Retrofit对象

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("请求基地址/")
            //可以接收自定义的Gson
            //Retrofit会使用Gson将ResponseBody
            .addConverterFactory(GsonConverterFactory.create())
            .build();

Retrofit retrofit = new Retrofit.Builder()
      .baseUrl(ServerInterface.BASE_URL)
      .addConverterFactory(ScalarsConverterFactory.create())//解析成字符串
      .build();

3、定义请求接口

public interface IRegister {
    @POST("接口路径")
@FormUrlEncoded //键值对
  Call<请求原型RegisterBean> register(@Field("请求参数Key user.name") String username, @Field("user.passWord") String password);

}
public interface IUpdate {
//完善资料,需要上传用户头像
@POST(ServerInterface.USER_UPDATE)
@Multipart //表单数据
//文件上传,文件不带Part()
Call<String> userUpdate(@Part MultipartBody.Part doc,
@Part("user.id")String userId,
@Part("user.userName")String nickName,
@Part("user.sex")String sex,
@Part("user.myInfo")String info);
}

4、创建请求对象
IRegiter service = retrofit.create(IRegister.class)
Call<RegisterBean> call = service.register(username, password);
 
文件上传
File file = new File(path文件地址);

//将文件写入body请求内容体
//HTTP contentType 对照表
RequestBody body = RequestBody.create(MediaType.parse("image/jpg"),file);
//使用内容体去创建一个表单对象 image/*表示所有图片
MultipartBody.Part doc = MultipartBody.Part.createFormData("doc",file.getName(),body);
Call<String> call = retrofit.create(IUpdate.class).userUpdate(doc, userId, nickName, sex, myInfo);

5、执行
使用okHttp的的执行流程、


同步 堵塞线程

Response<RegisterBean> execute = call.execute();

异步

call.enqueue(new Callback<
RegisterBean>(){回调};



call.cancel();

Retrofit注解

Retrofit 共22个注解

1.HTTP请求方法
方法注解同Http请求模式 GET,POST,PUT,DELETE,PATCH,HEAD,OPTIONS,
可用HTTP来代替上面七个方法,HTTP有三个属性method ,path ,hasBody 。

2.Http请求类型
FormUrlEncoded Http默认请求方式,键值对。application/x-www-from-urlencoded
Multipart 带文件上传 from-data
Streaming 流类型返回

3.请求参数
Headers 添加请求头
Header 添加不固定值的Header
Field   Post普通键值对
FiledMap   Post普通键值对

Part Post文件上传
PartMap Post多文件上传


Query Get请求
QueryMap Get请求
Url
用于URL

Retrofit转换

GsonConverterFactory
当使用该转换器时,自动将返回json转换成Bean对象,但如果需要获取字符串会出错,需要使用下面转换器

ScalarsConverterFactory

官方提供的字符串转换工具

    compile 'com.squareup.retrofit2:converter-scalars:2.0.0'

原文地址:https://www.cnblogs.com/Claire6649/p/6120773.html