【问题标题】:Adding header to retrofit call request将标头添加到改造调用请求
【发布时间】:2026-02-01 07:35:02
【问题描述】:

我正在开发一个连接到 VPN 的 Android 应用。

我正在向 rest api 发送改造请求:

private void login_Request(){


        Log.d("ESTOY EN LOGIN REQUEST","ESTOY EN LOGIN REQUEST");
        LoginRequest loginRequest = new LoginRequest("HALEJANDRO","ALEJANDR0123","password","19.3509","-99.1566");

        Call <LoginRequest> call = jsonPlaceHolderApi.createLoginReques(loginRequest);
        call.enqueue(new Callback<LoginRequest>() {
            @Override
            public void onResponse(Call<LoginRequest> call, Response<LoginRequest> response) {


                Log.d("ESTOY EN LOGIN REQUEST","ESTOY EN LOGIN REQUEST rsponse "+response);


                if (!response.isSuccessful()) {
                    textViewResult.setText("Code: " + response.code());
                    return;
                }

                List<Login> login = (List<Login>) response.body();

                for (Login loginResponse : login ){
                    String content = "";
                    content += "Access Token: " + loginResponse.getAccess_topken() + "\n";
                    content += "Token Type: " + loginResponse.getToken_type() + "\n";


                    textViewResult.append(content);

                }

            }

            @Override
            public void onFailure(Call<LoginRequest> call, Throwable t) {

            }
        });
    }

现在我需要在请求中添加一个标头。

标题应该如下:

Content-Type=application/x-www-form-urlencoded

我一直在寻找一种将标头添加到请求中的方法,但我没有可以在我的情况下实施的解决方案。

编辑

这是界面:

导入 java.util.List;

导入 retrofit2.Call; 导入改造2.http.Body; 导入改造2.http.GET; 导入改造2.http.Headers; 导入改造2.http.POST;

public interface JsonPlaceHolderApi {

    @GET("posts")
    Call<List<Post>> getPosts();

    @POST("token")
    @Headers("Content-Type:application/x-www-form-urlencoded")
    Call <LoginRequest>createLoginRequest(@Body LoginRequest loginRequest);
}

编辑邮递员请求

第 1 部分

第 2 部分

第三部分

【问题讨论】:

    标签: android retrofit2


    【解决方案1】:

    您可以对任何标头值进行硬编码,如下所示

    @POST("auth")
    @Headers("Any value")
    fun createLoginRequest(@Body credentials: Credentials): Observable<Response<User>>
    

    欲了解更多信息,请参阅this link

    在您的情况下,x-www-form-urlencoded 请求应该像this 示例一样处理:

    public interface TaskService {  
        @FormUrlEncoded
        @POST("tasks")
        Call<Task> createTask(@Field("title") String title);
    }
    

    【讨论】:

    • 谢谢。我已在我的界面中包含您的建议,如下所示: @POST("token") @Headers("Content-Type:application/x-www-form-urlencoded") 调用 createLoginRequest(@Body LoginRequest loginRequest);
    • 但我从 API 收到一条错误消息:Response{protocol=http/1.1, code=400, message=Bad Request, url=10.128.0.2:5000/token
    • 我正在使用 Rest API 客户端(如 Postman)检查标头和参数,它使用相同的标头和参数
    • 当您发送的有效负载不是期望服务器的有效负载时,通常会发生 400。你的 LoginRequest 对象是什么样的?
    • 我知道,这就是我使用 Postman 检查参数键和值的原因,他们在 Postman 工作
    最近更新 更多