【问题标题】:Retrofit get String response改造获取字符串响应
【发布时间】:2016-10-02 01:21:47
【问题描述】:

是否可以使用 Retrofit 库仅接收字符串响应?我有一种情况,我需要在我的链接上添加查询,以便链接看起来像: localhost//注册?handle=SomeID

SomeID 是整数,当我这样做时,我会从服务器收到由 20 个字符组成的字符串格式的响应。我怎样才能得到这样的回应? Retrofit 甚至可以处理非 Json 格式的响应吗?

我应该如何创建这个:

@GET("/api/UserMainInformations") 调用 getUserMainInfo();

这是来自其他电话的示例,但现在我没有任何模型可以发送它,因为我只将它添加到查询中。我应该在 Call 中添加什么;

【问题讨论】:

  • 不要发送带有不相关标签的垃圾邮件

标签: android retrofit android-networking


【解决方案1】:

您可以从 api 获取响应并将其转换为字符串,如下所示:

 public interface RetrofitService{
        @GET("/users")
        Call<ResponseBody> listRepos();//function to call api
    }

    RetrofitService service = retrofit.create(RetrofitService.class);
    Call<ResponseBody> result = service.listRepos(username);
    result.enqueue(new Callback<ResponseBody>() {

    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());//convert reponse to string
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

【讨论】:

  • ResponseBody 是 OkHttp3 类。
【解决方案2】:

试试这个:

API接口:

public interface APIService {
@GET("api/get_info")
    Call<ResponseBody> getInfo();//import okhttp3.ResponseBody;
}

API 调用:

// Retrofit service creation code skipped here
String json = retrofitService().getInfo().execute().body().string();

它对我有用。我使用改造:2.1.0。

【讨论】:

    猜你喜欢
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 2019-12-20
    • 2017-10-21
    • 1970-01-01
    相关资源
    最近更新 更多