java retrofit2_Java Retrofit2使用

本文使用eclipse编辑器,gradle依赖jar,如若未配置此环境,请转Java Eclipse配置gradle编译项目配置好环境后再查看此文

在build.gradle文件中添加一下依赖

compile 'com.squareup.retrofit2:adapter-rxjava:2.3.0'

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

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

定义java bean,bean中的变量名要与返回的json数据中的key保持一致,否则会匹配不上。

// 1. 定义java bean

/**

* Java Bean

*/

public class Info {

int error_code; // 状态码

String reason; // 返回状态文字

Result result; // 页面URL

@Override

public String toString() {

return "Info [error_code=" + error_code + ", reason=" + reason + ", result=" + result.toString() + "]";

}

}

/**

* Java Bean

*/

public class Result {

String h5url;

String h5weixin;

@Override

public String toString() {

return "Result [h5url=" + h5url + ", h5weixin=" + h5weixin + "]";

}

}

定义接口。

static String url = "http://v.juhe.cn/"; // 请求链接

static String KEY = "9488373060c8483a3ef6333353fdc7fe"; // 请求参数

// 2. 定义接口

public interface InfoService{

@GET("wepiao/query")

Call getInfo(

@Query(value = "key")

String key

);

}

4.获取Retrofit实例

// 3. 获取实例

Retrofit retrofit = new Retrofit.Builder()

// 设置OKHttpClient,如果不设置会提供一个默认的

.client(new OkHttpClient())

//设置baseUrl

.baseUrl(url)

//添加Gson转换器

.addConverterFactory(GsonConverterFactory.create())

.build();

执行retrofit.create方法

// 4. 执行retrofit.create方法

InfoService infoService = retrofit.create(InfoService.class);

执行同步请求

// 5. 执行请求

Call call = infoService.getInfo(KEY);

Response response = call.execute();

// 6. 判断是否成功,成功则打印出数据

if (response.isSuccessful()) {

Info info = response.body();

System.out.println(info.toString());

}

执行异步请求

// 5. 执行请求

Call call = infoService.getInfo(KEY);

call.enqueue(new Callback() {

public void onResponse(Call call, Response response) {

Info info = response.body();

System.out.println(info);

}

public void onFailure(Call call, Throwable t) {

System.out.println(t.getMessage());

}

});

retrofit注解:

方法注解,包含@GET、@POST、@PUT、@DELETE、@PATH、@HEAD、@OPTIONS、@HTTP。

标记注解,包含@FormUrlEncoded、@Multipart、@Streaming。

参数注解,包含@Query,@QueryMap、@Body、@Field,@FieldMap、@Part,@PartMap。

其他注解,@Path、@Header,@Headers、@Url。

几种特殊的注解

@HTTP:可以替代其他方法的任意一种

/**

* method 表示请的方法,不区分大小写

* path表示路径

* hasBody表示是否有请求体

*/

@HTTP(method = "get", path = "users/{user}", hasBody = false)

Call getFirstBlog(@Path("user") String user);

@Url:使用全路径复写baseUrl,适用于非统一baseUrl的场景。

@GET

Call v3(@Url String url);

@Streaming:用于下载大文件

@Streaming

@GET

Call downloadFileWithDynamicUrlAsync(@Url String fileUrl);

ResponseBody body = response.body();

long fileSize = body.contentLength();

InputStream inputStream = body.byteStream();

常用注解

@Path:URL占位符,用于替换和动态更新,相应的参数必须使用相同的字符串被@Path进行注释

@GET("group/{id}/users")

Call> groupList(@Path("id") int groupId);

//--> http://baseurl/group/groupId/users

//等同于:

@GET

Call> groupListUrl(

@Url String url

);

@Query,@QueryMap:查询参数,用于GET查询,需要注意的是@QueryMap可以约定是否需要encode

@GET("group/users")

Call> groupList(@Query("id") int groupId);

//--> http://baseurl/group/users?id=groupId

Call> getNews((@QueryMap(encoded=true) Map options);

@Body:用于POST请求体,将实例对象根据转换方式转换为对应的json字符串参数,这个转化方式是GsonConverterFactory定义的。

@POST("add")

Call> addUser(@Body User user);

@Field,@FieldMap:Post方式传递简单的键值对,需要添加@FormUrlEncoded表示表单提交Content-Type:application/x-www-form-urlencoded.

@FormUrlEncoded

@POST("user/edit")

Call updateUser(@Field("first_name") String first, @Field("last_name") String last);

@Part,@PartMap:用于POST文件上传

其中@Part MultipartBody.Part代表文件,@Part("key") RequestBody代表参数

需要添加@Multipart表示支持文件上传的表单,Content-Type: multipart/form-data.

@Multipart

@POST("upload")

Call upload(@Part("description") RequestBody description, @Part MultipartBody.Part file);

// https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java

// use the FileUtils to get the actual file by uri

File file = FileUtils.getFile(this, fileUri);

// create RequestBody instance from file

RequestBody requestFile =

RequestBody.create(MediaType.parse("multipart/form-data"), file);

// MultipartBody.Part is used to send also the actual file name

MultipartBody.Part body =

MultipartBody.Part.createFormData("picture", file.getName(), requestFile);

// add another part within the multipart request

String descriptionString = "hello, this is description speaking";

RequestBody description =

RequestBody.create(

MediaType.parse("multipart/form-data"), descriptionString);

@Header:header处理,不能被互相覆盖,用于修饰参数

//动态设置Header值

@GET("user")

Call getUser(@Header("Authorization") String authorization)

等同于

//静态设置Header值

@Headers("Authorization: authorization")//这里authorization就是上面方法里传进来变量的值

@GET("widget/list")

Call getUser()

@Headers 用于修饰方法,用于设置多个Header值

@Headers({

"Accept: application/vnd.github.v3.full+json",

"User-Agent: Retrofit-Sample-App"

})

@GET("users/{username}")

Call getUser(@Path("username") String username);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值