2016-04-09 37 views
9

Sto facendo android, cercando un modo per fare una richiesta HTTP GET/POST super base. Continuo a ricevere un errore:Come ottenere una risposta stringa da Retrofit2?

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

Webservice:

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

poi nella mia 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(); 

Sto letteralmente solo cercando di interrogare jquery.org/projects con un GET richiedi e restituisci la stringa con cui risponde. Che c'è?

Se provo a implementare un convertitore personalizzato (ho trovato alcuni esempi in linea) si lamenta che non ho implementato il metodo astratto convert (F), che nessuno degli esempi fa.

Grazie.

risposta

4

Dare un'occhiata alla libreria Retrofit e ho notato che analizza la risposta in base alla classe di tipo all'interno di Call<T>. Quindi hai due opzioni: 1 °: crea una classe in base alla risposta del server.

2: ottenere la risposta e gestirla da soli (non consigliato, Retrofit lo gestisce già, quindi perché utilizzare Retrofit poiché è adatto a questo lavoro). In ogni caso invece di utilizzo Call<String>Call<ResponseBody> e Call<ResponseBody> signin = service.jquery(); dopo questo mettere le seguenti

call.enqueue(new Callback<ResponseBody>() { 
    @Override 
    public void onResponse(Response<ResponseBody> response, Retrofit retrofit) { 
    // handle success 
    String result = response.body().string(); 

    } 

    @Override 
    public void onFailure(Throwable t) { 
    // handle failure 
    } 
}); 
+0

Qual è collaboratore? Non riesce a trovarlo. –

+0

L'ho modificato È ResponseBody e altre modifiche sono body(). Stringa() – uguboz

3

Si può provare la seguente:

build.gradle di file:

dependencies { 
    ... 
    compile 'com.squareup.retrofit2:retrofit:2.0.1' 
    ... 
} 

WebAPIService:

file di 210

attività:

 Retrofit retrofit = new Retrofit.Builder() 
       .baseUrl(API_URL_BASE)      
       .build(); 

     WebAPIService service = retrofit.create(WebAPIService.class); 

     Call<String> stringCall = service.getValues(); 
     stringCall.enqueue(new Callback<String>() { 
      @Override 
      public void onResponse(Call<String> call, Response<String> response) { 
       Log.i(LOG_TAG, response.body()); 
      } 

      @Override 
      public void onFailure(Call<String> call, Throwable t) { 
       Log.e(LOG_TAG, t.getMessage()); 
      } 
     }); 

ho provato con il mio Web serivce (ASP.Net WebAPI):

public class ValuesController : ApiController 
{ 
     public string Get() 
     { 
      return "value1"; 
     } 
} 

Android Logcat out: 04-11 15:17:05.316 23097-23097/com.example.multipartretrofit I/AsyncRetrofit2: value1

Speranza che aiuta!

3

Per ottenere la risposta come stringa, è necessario scrivere un convertitore e passarlo durante l'inizializzazione di Retrofit.

Ecco i passaggi.

Inizializzazione del retrofit.

Retrofit retrofit = new Retrofit.Builder() 
       .baseUrl(API_URL_BASE) 
       .addConverterFactory(new ToStringConverterFactory()) 
       .build(); 
     return retrofit.create(serviceClass); 

classe Converter per la conversione Retrofit's ResponseBody al String

public class ToStringConverterFactory extends Converter.Factory { 
    private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain"); 


    @Override 
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, 
                  Retrofit retrofit) { 
     if (String.class.equals(type)) { 
      return new Converter<ResponseBody, String>() { 
       @Override 
       public String convert(ResponseBody value) throws IOException 
       { 
        return value.string(); 
       } 
      }; 
     } 
     return null; 
    } 

    @Override 
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, 
                  Annotation[] methodAnnotations, Retrofit retrofit) { 

     if (String.class.equals(type)) { 
      return new Converter<String, RequestBody>() { 
       @Override 
       public RequestBody convert(String value) throws IOException { 
        return RequestBody.create(MEDIA_TYPE, value); 
       } 
      }; 
     } 
     return null; 
    } 
} 

E dopo l'esecuzione service.jquery();, signin conterrà risposta JSON.

20

Con Retrofit2 aggiungi ScalarsConverterFactory al tuo Retrofit.Builder.

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

Per utilizzare ScalarsCoverter aggiungere seguente dipendenza al vostro costruire graddle

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

Per uso API chiamata: ``

Call <String> ***** 

Codice Android:

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

risposta eccellente ... l'aggiunta di una singola riga di .addConverterFactory (ScalarsConverterFactory.create()) ha risolto il problema ... –

+0

ottimo, funziona per response.body(). toString(). ma in caso di response.errorBody(). toString() non funziona, pls help me –

0
String body = new String(((TypedByteArray) response.getBody()).getBytes()); 

se hai trovato

java.lang.ClassCastException: retrofit.client.UrlConnectionClient$TypedInputStream cannot be cast to retrofit.mime.TypedByteArray 

poi mettere questo nel vostro RestAdapter

   .setLogLevel(RestAdapter.LogLevel.FULL) 

per esempio:

RestAdapter restAdapter = new RestAdapter.Builder() 
      .setLogLevel(RestAdapter.LogLevel.FULL) 
      .setEndpoint(Root_url) 
      .build(); 
Problemi correlati