android - 使用 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 的值并粘贴到浏览器中,它工作正常。
问候
解决方案
尝试更换
@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);
}
});
推荐阅读
- python - 创建一个包含每个事务文件的列表
- haskell - 类型变量条件下的 Haskell 实例
- python - 使用远程解释器在服务器上运行 Django - 防止 Django 创建测试数据库
- php - Phpword - 使用模板处理器添加图像
- r - gghighlight 2 具体点 ggplot2
- emacs - emacs - 是否可以将 defs 与 clojure-mode 对齐?
- javascript - 有必要(重新?)在这里使用“var”吗?
- sql-server - 组合 2 个查询以获得单组结果的问题
- google-app-engine - Google App Engine Go 1.11 应用程序无法访问 Google 电子表格
- c# - Excel 中使用 Open XML 的样式