How to get string response from Retrofit2?

前端 未结 10 1477
时光取名叫无心
时光取名叫无心 2020-12-01 07:44

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 creat         


        
相关标签:
10条回答
  • 2020-12-01 07:47
        call.enqueue(new Callback<Object>() {
            @Override
            public void onResponse(@NonNull Call<Object> call, @NonNull Response<Object> response) {
                if (response.isSuccessful()) {
                    Gson gson = new Gson();
                    String successResponse = gson.toJson(response.body());
                    Log.d(LOG_TAG, "successResponse: " + successResponse);
                } else {
                    try {
                        if (null != response.errorBody()) {
                            String errorResponse = response.errorBody().string();
                            Log.d(LOG_TAG, "errorResponse: " + errorResponse);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
    
            @Override
            public void onFailure(@NonNull Call<Object> call, @NonNull Throwable t) {
            }
        });
    
    0 讨论(0)
  • 2020-12-01 07:48

    You can try the following:

    build.gradle file:

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

    WebAPIService:

    @GET("/api/values")
    Call<String> getValues();
    

    Activity file:

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

    I have tested with my 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

    Hope it helps!

    0 讨论(0)
  • 2020-12-01 07:55

    To get the response as a String, you have to write a converter and pass it when initializing Retrofit.

    Here are the steps.

    Initializing retrofit.

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

    Converter class for converting Retrofit's ResponseBody to 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;
        }
    }
    

    And after executing service.jquery();, signin will contain JSON response.

    0 讨论(0)
  • 2020-12-01 07:55

    make sure its JsonObject not a JSONObject

    Call<JsonObject> call = api.getJsonData(url);
        call.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                String str = response.body().toString();
                Log.e(TAG, "onResponse: " + str);
            }
    
            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                Log.e(TAG, "onFailure: " + t.getMessage());
    
            }
        });
    

    By using JsonObject you can get any type of response in string format.

    0 讨论(0)
  • 2020-12-01 07:56

    thought it might be late to answer just use response.body()?.string() and you'll have your response as a string.

    0 讨论(0)
  • 2020-12-01 08:02

    Just use log level BODY in intercepror:

            OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()....
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            clientBuilder.addNetworkInterceptor(httpLoggingInterceptor);
    

    And you can see body in logcat like:

            D/OkHttp: {"blablabla":1,.... }
            D/OkHttp: <-- END HTTP (1756-byte body)
    

    This solution for debug only, not for get String directly in code.

    0 讨论(0)
提交回复
热议问题