首页 > 解决方案 > 使用 url + json 返回方法改造 POST 方法不允许

问题描述

我的 POST API 是这样的:https://out-test.com/test/out/{ "key":"value" }

当我在浏览器中复制粘贴 URL 时没有任何问题,它会接受它。但在 Android 中,我得到了一个响应Method Not Allowed

我的 API 调用:

@POST
Call<OUT> updateOUT( @Url String urlWithJson );

改造声明:

     //  Retrofit2 implementation
    String BASE_API_URL = "https://out-test.com/";
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl( BASE_API_URL )
            .addConverterFactory( GsonConverterFactory.create() )
            .build();

    final OutAPI api = retrofit.create( OutAPI.class );

将对象解析为字符串(我得到了正确的 JSON,我已经验证了它):

 Gson gson = new Gson();
            String jsonString = gson.toJson(out);
            String url = "test/out/" + jsonString;

然后我打电话给 POST :

 api.updateOut( url ).enqueue(new Callback<Out>() {
    @Override
    public void onResponse(Call<Out> call, Response<Out> response) {
       Log.d(TAG, "onResponse:" + response );
    }

    @Override
    public void onFailure(Call<Out> call, Throwable t) {
        Log.d(TAG, "onFailure: " + t);
    }
 });

有谁知道我在这里做错了什么才能得到这个回复?我错过了什么吗?在互联网上搜索,但没有找到任何有效的解决方案。

@EDIT:当我调试并查看响应和 URL 时,如果我复制 URL 的值并粘贴到浏览器中,它工作正常。

问候

标签: androidretrofitretrofit2

解决方案


尝试更换

@POST
Call<OUT> updateOUT( @Url String urlWithJson );

这与以下。

@POST("test/out/{key_value}")
Call<OUT> updateOUT(@Path("key_value") String keyAndValue);

然后,如下更新其余代码

//  Retrofit2 implementation

String BASE_API_URL = "https://out-test.com/";
Retrofit retrofit = new Retrofit.Builder()
            .baseUrl( BASE_API_URL )
            .addConverterFactory( GsonConverterFactory.create() )
            .build();

final OutAPI api = retrofit.create( OutAPI.class );

Gson gson = new Gson();
String jsonString = gson.toJson(out);

api.updateOut(jsonString).enqueue(new Callback<Out>() {
    @Override
    public void onResponse(Call<Out> call, Response<Out> response) {
       Log.d(TAG, "onResponse:" + response );
    }

    @Override
    public void onFailure(Call<Out> call, Throwable t) {
        Log.d(TAG, "onFailure: " + t);
    }
 });

推荐阅读