This question already has an answer here:
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.
** 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 --
Add the
ScalarsConverterFactory
to your retrofit builder. Note: If usingScalarsConverterFactory
and another factory, add the scalars factory first.You will also need to include the scalars converter in your gradle file --
--- 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 gsonTypeAdapter
or a retrofitConverter
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, useResponseBody
from okhttp --then you can create and execute your call --
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 callcharStream()
instead. See theResponseBody
docs.