首页 > 解决方案 > 发送参数和正文行空改造

问题描述

我正在尝试使用 Retrofit2 Android 库调用需要的服务:

我的界面是这样的:

    @Headers({
            "Accept: application/json",
            "Content-Type: application/json"
    })
    @FormUrlEncoded
    @POST("/nameOfAction")
    Call<ItemResponse> callAction(@Header("Authorization") String authorization, @Field("nameOfParameter") String nameOfParameter);

我用这段代码调用它:

 ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

        Call<CarrelloResponse> call = apiService.callAction( "Bearer " + tokenAccess, "valueOfParameter");

        call.enqueue(new Callback<ItemResponse>() {
            @Override
            public void onResponse(Call<ItemResponse> call, Response<ItemResponse> response) {

                int statusCode = response.code();

                if (statusCode == 200) {
                    if (response.isSuccessful()) {
                        // code
                    } else {
                        Log.e(TAG, response.errorBody().toString());
                    }
                } 
            }

            @Override
            public void onFailure(Call<ItemResponse> call, Throwable t) {
                Log.e(TAG, t.toString());

            }
        });

但它不起作用,因为我还需要发送 body raw 空的工作。

如果我用 Postman 发送它,如下图所示:

在此处输入图像描述

任何建议将不胜感激。

标签: androidretrofit2

解决方案


尝试像这样删除@FormUrlEncoded并更改@Field@Query参数

@Headers({
        "Accept: application/json",
        "Content-Type: application/json"
})
@POST("/nameOfAction")
Call<ItemResponse> callAction(@Header("Authorization") String authorization, @Query("nameOfParameter") String nameOfParameter);

********由 OP 编辑​​ *******

在 nameOfAction 的末尾添加斜线它也可以将 @Field 更改为 @Query:

    @Headers({
            "Accept: application/json",
            "Content-Type: application/json"
    })
    @POST("nameOfAction/")
    Call<ItemResponse> callAction(@Header("Authorization") String authorization, @Query("nameOfParameter") String nameOfParameter);

推荐阅读