How to get response as String using retrofit without using GSON or any other library in android

Aakash picture Aakash · Sep 16, 2015 · Viewed 105.7k times · Source

I am trying to get response from the following Api :

https://api.github.com/users/username

But I don't know how to get response as String so that I can use the String to parse and get the JSONObject.

Retrofit version used:

retrofit:2.0.0-beta1

I have tried this until now:

public interface GitHubService {
        @GET("/users/{user}")
        public String listRepos(@Path("user") String user,Callback<String> callback);
    }

retrieving :

GitHubService service = retrofit.create(GitHubService.class);
        service.listRepos("username", new Callback<String>() {
            @Override
            public void onResponse(Response response) {
                System.out.println(response.toString());
            }

            @Override
            public void onFailure(Throwable t) {

            }
        });

exception:

Caused by: java.lang.IllegalArgumentException: Could not locate call adapter for class java.lang.String. Tried:
    * retrofit.ExecutorCallAdapterFactory
            at retrofit.Utils.resolveCallAdapter(Utils.java:67)
            at retrofit.MethodHandler.createCallAdapter(MethodHandler.java:49)

Any help would be really appreciated.

Answer

iagreen picture iagreen · Sep 17, 2015

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.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());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.