Retrofit 2 request body 没有 json,只是一个普通的形式?

Retrofit 2 request body without json, just a normal form?

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

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

我已经尝试了所有我能找到的tutorial/example。

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); 
}

我是这样用的

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)

这样你就可以为 post 使用 FormURLEncoded 方法。此外,Retrofit 还提供了一些方法来覆盖 ResponseBodyRequestBody 的默认转换器。如文档中所述:

Retrofit Configuration

Retrofit is the class through which your API interfaces are turned into callable objects. By default, Retrofit will give you sane defaults for your platform but it allows for customization.

CONVERTERS

By default, Retrofit can only deserialize HTTP bodies into OkHttp's ResponseBody type and it can only accept its RequestBody type for @Body.

Converters can be added to support other types. Six sibling modules adapt popular serialization libraries for your convenience.

Gson: com.squareup.retrofit2:converter-gson Jackson: com.squareup.retrofit2:converter-jackson Moshi: com.squareup.retrofit2:converter-moshi Protobuf: com.squareup.retrofit2:converter-protobuf Wire: com.squareup.retrofit2:converter-wire Simple XML: com.squareup.retrofit2:converter-simplexml Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars Here's an example of using the GsonConverterFactory class to generate an implementation of the GitHubService interface which uses Gson for its deserialization.

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

GitHubService service = retrofit.create(GitHubService.class);

CUSTOM CONVERTERS

If you need to communicate with an API that uses a content-format that Retrofit does not support out of the box (e.g. YAML, txt, custom format) or you wish to use a different library to implement an existing format, you can easily create your own converter. Create a class that extends the Converter.Factory class and pass in an instance when building your adapter.

希望对您有所帮助