【问题标题】:How to get the response from Retrofit POST request如何从 Retrofit POST 请求中获取响应
【发布时间】:2018-10-18 18:14:16
【问题描述】:

我正在修复一个损坏的项目,我正在尝试修复其中一个功能。

我需要解决使用 Retrofit 发布一个带有数据的帖子,然后接收信息的响应。

public interface GetDataService {

@FormUrlEncoded
@POST("pocketdeal/togetallfavorites")
Call<Favourite> getFavorite();

}

获取收藏信息的方法

     public void MyFavoriteDeals4(String title, String body) {

    //(title, body, 1) is the method for adding things
    mAPIService.getFavorite().enqueue(new Callback<Post>() {
        @Override
        public void onResponse(Call<Post> call, Response<Post> response) {

            if(response.isSuccessful()) {
                showResponse(response.body().toString());
                Log.e("Favorites", "Successful");
            }
        }

        @Override
        public void onFailure(Call<Post> call, Throwable t) {
            Log.e("Favorites", "Failure");
        }
    });
}

我没有得到响应或失败,也没有使用我需要的所有信息。另外,在网上发布我的 API 信息是不是很糟糕?

我需要用到的信息..

我的帖子数据: lat=37.785834&long=-122.406417&android_id=1AC7C092-AC45-419F-AFED-3D2FEE473750&timezone=美国/温哥华

我的网址:出于隐私考虑已删除

请求标头:Content-Type with application/x-www-form-urlencoded

我已经在 API 测试仪中在线测试了所有这些,所以我知道如果操作正确,它会产生正确的结果

【问题讨论】:

    标签: java android rest retrofit2


    【解决方案1】:

    当您使用 @FormUrlEncoded 时,您应该使用 Field 注释添加您的参数:

    public interface GetDataService {
    
    @FormUrlEncoded
    @POST("pocketdeal/togetallfavorites")
    Call<Favourite> getFavorite(@Field("lat") Long lat, @Field("long") Long lng, @Field("android_id") String androidId, @Field("timezone") String timezone);
    
    }
    

    你应该像这样初始化你的改造调用:

    Call<Favourite> call2 = favouriteInterfacemAPIService.getFavorite(37.785834, -122.406417, "1AC7C092-AC45-419F-AFED-3D2FEE473750", "America/Vancouver");
    

    【讨论】:

    • 再次更新,无响应或失败,未包含我的帖子数据
    • 我留下空白只是为了让测试正常工作,但没有它我无法得到回复,非常感谢您的帮助。这解决了一切。
    猜你喜欢
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    相关资源
    最近更新 更多