Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get string response from Retrofit2?

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.

like image 400
Matthew Darnell Avatar asked Apr 09 '16 23:04

Matthew Darnell


People also ask

How do I get retrofit response in HTML?

Retrofit uses a converter to process responses from endpoints and requests as well. By default, Retrofit uses GsonConverter, which encoded JSON responses to Java objects using the gson library. You can override that to supply your own converter when constructing your Retrofit instance.


1 Answers

Add Retrofit2 and 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

implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'  implementation 'com.squareup.retrofit2:retrofit:2.9.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();             }         } 
like image 112
Neyomal Avatar answered Oct 07 '22 00:10

Neyomal