Java - Retrofit 2 请求良好实践
Java - Retrofit 2 requests good practices
我目前正在对 Android 应用程序进行改造。
这对我来说很新,我正在尝试找出处理简单请求而又不会弄乱的最佳方法。
我的客户端正在使用 JSON(改造的 JacksonConverter)与我的服务器通信。
所以现在,我最终做了这样的事情:
public interface MyWebService {
class RequestLogin {
public String email;
public String hash;
public RequestLogin(String email, String hash) {
this.email = email;
this.hash = hash;
}
}
@POST("/login")
Call<String> login(@Body RequestLogin body);
}
public void someFunction() {
Call<String> call = serviceInstance.login(new RequestLogin("some_mail", "some_hash"));
}
在这里你可以看到我的 /login
路线采用简单的 JSON:
{
"email": "some_email_here",
"hash": "some_passwd_hash_here"
}
和returns正文中的一个简单字符串。
还不错,但恐怕事情会随着时间的推移变得一团糟。
创建对象是使用改造在请求主体内使用 JSON 的唯一方法吗?
也许有一种方法可以代替:
@POST("/login")
Call<String> login(@MagicTag String email, @MagicTag String hash);
我可能从图书馆的 javadoc 中遗漏了它,但是当您从未使用过它时,网站不是很清楚。如果它存在,我没有找到任何使用它的样本。
在:http://square.github.io/retrofit/:
表单编码和多部分
也可以声明方法来发送表单编码和多部分数据。
当@FormUrlEncoded 出现在方法上时,发送表单编码数据。每个键值对都用@Field 注释,其中包含名称和提供值的对象。
@FormUrlEncoded
@POST("/user/edit")
Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);
在你的情况下应该是:
@FormUrlEncoded
@POST("/login")
Call<String> login(@Field("email") String email, @Field("hash") String hash);
希望对您有所帮助!
我目前正在对 Android 应用程序进行改造。 这对我来说很新,我正在尝试找出处理简单请求而又不会弄乱的最佳方法。
我的客户端正在使用 JSON(改造的 JacksonConverter)与我的服务器通信。 所以现在,我最终做了这样的事情:
public interface MyWebService {
class RequestLogin {
public String email;
public String hash;
public RequestLogin(String email, String hash) {
this.email = email;
this.hash = hash;
}
}
@POST("/login")
Call<String> login(@Body RequestLogin body);
}
public void someFunction() {
Call<String> call = serviceInstance.login(new RequestLogin("some_mail", "some_hash"));
}
在这里你可以看到我的 /login
路线采用简单的 JSON:
{
"email": "some_email_here",
"hash": "some_passwd_hash_here"
}
和returns正文中的一个简单字符串。
还不错,但恐怕事情会随着时间的推移变得一团糟。
创建对象是使用改造在请求主体内使用 JSON 的唯一方法吗?
也许有一种方法可以代替:
@POST("/login")
Call<String> login(@MagicTag String email, @MagicTag String hash);
我可能从图书馆的 javadoc 中遗漏了它,但是当您从未使用过它时,网站不是很清楚。如果它存在,我没有找到任何使用它的样本。
在:http://square.github.io/retrofit/:
表单编码和多部分
也可以声明方法来发送表单编码和多部分数据。
当@FormUrlEncoded 出现在方法上时,发送表单编码数据。每个键值对都用@Field 注释,其中包含名称和提供值的对象。
@FormUrlEncoded
@POST("/user/edit")
Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);
在你的情况下应该是:
@FormUrlEncoded
@POST("/login")
Call<String> login(@Field("email") String email, @Field("hash") String hash);
希望对您有所帮助!