Retrofit2笔记

2017-07-22  本文已影响0人  andyfeng

一、Retrofit使用

定义接口

public interface GitHub {

@GET("/repos/{owner}/{repo}/contributors")

Call<List<Contributor>> contributors(@Path("owner") String owner, @Path("repo") String repo);

}

Retrofit retrofit = new Retrofit.Builder().baseUrl("http://localhost:8080/").build();

GitHub github = retrofit.create(GitHub.class);

List contributors = call.execute().body();

地址以斜线结尾,注解中的地址不要以斜线开头.

二、Retrofit注解

1. GET相关

@GET("/repos/{owner}/{repo}/contributors")

Call> contributors(@Path("owner") String owner, @Path("repo") String repo);

result : contributors("square", "")

@Headers("Cache-Control: max-age=640000")

@GET("/")

@Headers({"X-Foo: Bar","X-Ping: Pong"})

@GET("/")

@GET("/")

Call foo(@Header("Accept-Language") String lang);

@GET("/search")

void list(@HeaderMap Map headers);

Accept: text/plain and Accept-Charset: utf-8

foo.list(ImmutableMap.of("Accept", "text/plain", "Accept-Charset", "utf-8"));

2. POST

除上述GET请求配置外,有Field, FieldMap,需要指定FormUrlEncoded

@FormUrlEncoded

@POST("/")

Call example(

@Field("name") String name,

@Field("occupation") String occupation);

Calling withfoo.example("Bob Smith", "President")yields a request body ofname=Bob+Smith&occupation=President.

@FormUrlEncoded

@POST("/things")

Call things(@FieldMap Map fields);

Calling withfoo.things(ImmutableMap.of("foo", "bar", "kit", "kat")yields a request body offoo=bar&kit=kat.

@Body 发送json格式POST body

上一篇下一篇

猜你喜欢

热点阅读