【问题标题】:Retrofit 2 request body without json, just a normal form?改造 2 没有 json 的请求体,只是一个普通的形式?
【发布时间】:2016-02-18 09:35:30
【问题描述】:

我看到的每个示例和教程都展示了如何将请求正文转换为 JSON,这不是我所需要的。

这在我的场景中无效,因为我没有与节点或 w/e 交谈,我会浪费计算。我必须在我的应用程序中转换为 JSON,然后在后端从 JSON 解码,这需要一个常规形式,我没有理由这样做。

我已经尝试了所有我能找到的教程/示例。

public interface myClient {
    @GET("api/fetch-all")
    Call<List<ServiceGenerator.Data>> data();

    // How am I supposed to do this?
    @POST("api/login")
    Call<ServiceGenerator.Cookie> fetchCookie(@Body String email, String password); 
}

【问题讨论】:

    标签: android json retrofit2


    【解决方案1】:

    我是这样用的

    class User {
        String email;
        String password;
    
        public User(String email, String password) {
            this.email = email;
            this.password = password;
        }
    }
    

    然后就像你说的

    @FormUrlEncoded
    @POST("api/login")
    Call<User> fetchCookie(@Field("email") String email, @Field("password") String password);
    
    User user = new User("a@a.com", "1234");
    mService.fetchCookie(user.email, user.password)
    

    这样你最终会使用 FormURLEncoded 方法进行发布。 Retrofit 还提供了一些方法来覆盖 ResponseBodyRequestBody 的默认转换器。如文档中所述:

    改造配置

    Retrofit 是用于转换 API 接口的类 成可调用对象。默认情况下,Retrofit 会让你保持清醒 您的平台的默认设置,但它允许自定义。

    转换器

    默认情况下,Retrofit 只能将 HTTP 主体反序列化为 OkHttp 的 ResponseBody 类型,它只能接受它的 RequestBody 类型 @身体。

    可以添加转换器以支持其他类型。六个兄弟模块 为了您的方便,改编流行的序列化库。

    Gson: com.squareup.retrofit2:converter-gson Jackson: com.squareup.retrofit2:converter-jackson Moshi: com.squareup.retrofit2:converter-moshi Protobuf: com.squareup.retrofit2:converter-protobuf 电线: com.squareup.retrofit2:converter-wire 简单 XML: com.squareup.retrofit2:converter-simplexml 标量(原语,盒装, 和字符串):com.squareup.retrofit2:converter-scalars 这是一个 使用 GsonConverterFactory 类生成的示例 GitHubService 接口的实现,它使用 Gson 作为其 反序列化。

    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.github.com")
        .addConverterFactory(GsonConverterFactory.create())
        .build();
    
    GitHubService service = retrofit.create(GitHubService.class);
    

    自定义转换器

    如果您需要与使用以下内容格式的 API 通信 Retrofit 不支持开箱即用(例如 YAML、txt、自定义 格式)或者您希望使用不同的库来实现 现有格式,您可以轻松创建自己的转换器。创建一个 扩展 Converter.Factory 类并传入实例的类 构建适配器时。

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2018-04-04
      • 1970-01-01
      • 2016-12-08
      • 2018-06-05
      • 2018-02-24
      • 1970-01-01
      • 1970-01-01
      • 2019-05-20
      • 2017-05-01
      相关资源
      最近更新 更多