且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带字符串响应的改造

更新时间:2022-06-17 04:50:16

好的答案是编写自己的转换器.像这样:

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

public final class ToStringConverterFactory extends Converter.Factory {

            @Override
            public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
                //noinspection EqualsBetweenInconvertibleTypes
                if (String.class.equals(type)) {
                    return new Converter<ResponseBody, Object>() {

                        @Override
                        public Object convert(ResponseBody responseBody) throws IOException {
                            return responseBody.string();
                        }
                    };
                }

                return null;
            }

            @Override
            public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) {
                //noinspection EqualsBetweenInconvertibleTypes
                if (String.class.equals(type)) {
                    return new Converter<String, RequestBody>() {

                        @Override
                        public RequestBody convert(String value) throws IOException {
                            return RequestBody.create(MediaType.parse("text/plain"), value);
                        }
                    };
                }

                return null;
            }
        }

您必须使用此名称:

Retrofit adapter = new Retrofit.Builder()
                        .baseUrl("http://root.url.net/")
                        .addConverterFactory(new ToStringConverterFactory())
                        .build();

                registerAPI api = adapter.create(registerAPI.class);

                Call<String> call = api.insertUser(name,regid);

您会收到以下答复:

call.enqueue(new Callback<String>()
                {
                    @Override
                    public void onResponse(Response<String> 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());

                    }
                });