Retrofit with String response

前端 未结 2 1602
挽巷
挽巷 2021-01-18 17:24

I want a POST call on an URL, and as response I just get a String \"ok\" or \"no\".. So I have here my interface like this:

public interface registerAPI
{
           


        
2条回答
  •  粉色の甜心
    2021-01-18 17:26

    Ok the answer is to write an own converter. Like this:

    public final class ToStringConverterFactory extends Converter.Factory {
    
                @Override
                public Converter fromResponseBody(Type type, Annotation[] annotations) {
                    //noinspection EqualsBetweenInconvertibleTypes
                    if (String.class.equals(type)) {
                        return new Converter() {
    
                            @Override
                            public Object convert(ResponseBody responseBody) throws IOException {
                                return responseBody.string();
                            }
                        };
                    }
    
                    return null;
                }
    
                @Override
                public Converter toRequestBody(Type type, Annotation[] annotations) {
                    //noinspection EqualsBetweenInconvertibleTypes
                    if (String.class.equals(type)) {
                        return new Converter() {
    
                            @Override
                            public RequestBody convert(String value) throws IOException {
                                return RequestBody.create(MediaType.parse("text/plain"), value);
                            }
                        };
                    }
    
                    return null;
                }
            }
    

    You have to call it with this:

    Retrofit adapter = new Retrofit.Builder()
                            .baseUrl("http://root.url.net/")
                            .addConverterFactory(new ToStringConverterFactory())
                            .build();
    
                    registerAPI api = adapter.create(registerAPI.class);
    
                    Call call = api.insertUser(name,regid);
    

    You get the response in this:

    call.enqueue(new Callback()
                    {
                        @Override
                        public void onResponse(Response response, Retrofit retrofit)
                        {
                            Log.i("http","innen: " + response.message());
                            Log.i("http","innen: " + response.body()); // here is your string!!
                        }
    
                        @Override
                        public void onFailure(Throwable t)
                        {
                            Log.d("http", " Throwable " +t.toString());
    
                        }
                    });
    

提交回复
热议问题