Retrofit get String response

拟墨画扇 提交于 2019-11-27 06:38:58

问题


Is it possible to recieve only String response using Retrofit library? I have a situation where I need to add Query on my link so that link is looking like : localhost//Register?handle=SomeID

SomeID is integer and when I do that I will receive response from server in string format that consist of 20 chars. How can I get that response? Can Retrofit even handle response that is not in Json format?

Also how should I create this :

@GET("/api/UserMainInformations") Call getUserMainInfo();

That's example from some other call but now I won't have any model to send it cuz I only add it on Query. What should i put in Call<> ;


回答1:


You can get the response from api and convert it to string like this:

 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();
    }
});



回答2:


Try this:

Api interface:

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

Api call:

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

It worked for me. I use retrofit:2.1.0.



来源:https://stackoverflow.com/questions/37589588/retrofit-get-string-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!