Retrofit获取String响应

15 android android-networking retrofit

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

SomeID是整数,当我这样做时,我将以字符串格式从服务器接收包含20个字符的响应.我怎样才能得到答复?Can Retrofit甚至可以处理不是Json格式的响应吗?

另外我应该如何创建:

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

这是其他一些调用的例子,但现在我没有任何模型可以发送它因为我只在Query上添加它.我应该在Call <>中放什么

Sar*_*ern 20

您可以从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();
    }
});
Run Code Online (Sandbox Code Playgroud)

  • `ResponseBody` 是 OkHttp3 类。 (2认同)

Mik*_*ail 8

试试这个:

Api界面:

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

Api电话:

// Retrofit service creation code skipped here
String json = retrofitService().getInfo().execute().body().string();
Run Code Online (Sandbox Code Playgroud)

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