How to get string response from Retrofit2?

Matthew Darnell picture Matthew Darnell · Apr 10, 2016 · Viewed 55.7k times · Source

I am doing android, looking for a way to do a super basic http GET/POST request. I keep getting an error:

java.lang.IllegalArgumentException: Unable to create converter for class java.lang.String

Webservice:

public interface WebService {
    @GET("/projects")
    Call<String> jquery();
}

then in my java:

    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://jquery.org")
       // .addConverterFactory(GsonConverterFactory.create())
        .build();

    WebService service = retrofit.create(WebService.class);
    Call<String> signin = service.jquery();

    Toast.makeText(this, signin.toString(), Toast.LENGTH_LONG).show();

I'm literally just trying to query jquery.org/projects with a GET request and return the String that it responds with. What is wrong?

If I try to implement a custom Converter (I've found a few examples online) it complains that I didn't implement the abstract method convert(F), which none of the examples do.

Thanks.

Answer

Neyomal picture Neyomal · Feb 27, 2017

Add Retrofit2 add ScalarsConverterFactory to your Retrofit.Builder.

adapterBuilder = new Retrofit.Builder()
               .addConverterFactory(ScalarsConverterFactory.create())
               .addConverterFactory(GsonConverterFactory.create());

To use ScalarsCoverter add following dependency to your build graddle

compile 'com.squareup.retrofit2:converter-scalars:2.1.0'
compile 'com.squareup.retrofit2:retrofit:2.1.0' //Adding Retrofit2

For API Call use: ``

Call <String> *****

Android Code :

.enqueue(new Callback<String>() {
    @Override
    public void onResponse(Call<String> call, Response<String> response) {
        Log.i("Response", response.body().toString());
        //Toast.makeText()
        if (response.isSuccessful()){
            if (response.body() != null){
                Log.i("onSuccess", response.body().toString());
            }else{
                Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show();
            }
        }