How to get string response from Retrofit2?

前端 未结 10 1526
时光取名叫无心
时光取名叫无心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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 responseBodyConverter(Type type, Annotation[] annotations,
                                                                Retrofit retrofit) {
            if (String.class.equals(type)) {
                return new Converter() {
                    @Override
                    public String convert(ResponseBody value) throws IOException
                    {
                        return value.string();
                    }
                };
            }
            return null;
        }
    
        @Override
        public Converter requestBodyConverter(Type type, Annotation[] parameterAnnotations,
                                                              Annotation[] methodAnnotations, Retrofit retrofit) {
    
            if (String.class.equals(type)) {
                return new Converter() {
                    @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.

提交回复
热议问题