Skip to content

Instantly share code, notes, and snippets.

@tomkoptel
Last active April 15, 2019 12:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tomkoptel/35ea8dca7fca040d63f3 to your computer and use it in GitHub Desktop.
Save tomkoptel/35ea8dca7fca040d63f3 to your computer and use it in GitHub Desktop.
Retrofit 2.0 converter for plain/text requests
  interface RestApi {
      @Multipart
      @Headers({"Accept:text/plain"})
      @POST(value = "/j_spring_security_check")
      Call<com.squareup.okhttp.Response> authenticate(
        @Part(value = "username") String username,
        @Part(value = "password") String password
        @PartMap Map<String, String> params);
  }
final class StringConverterFactory implements Converter.Factory {
    private StringConverterFactory() {}

    public static StringConverterFactory create() {
        return new StringConverterFactory();
    }

    @Override
    public Converter<String> get(Type type) {
        Class<?> cls = (Class<?>) type;
        if (String.class.isAssignableFrom(cls)) {
            return new StringConverter();
        }
        return null;
    }

    private static class StringConverter implements Converter<String> {
        private static final MediaType PLAIN_TEXT = MediaType.parse("text/plain; charset=UTF-8");

        @Override
        public String fromBody(ResponseBody body) throws IOException {
            return new String(body.bytes());
        }

        @Override
        public RequestBody toBody(String value) {
            return RequestBody.create(PLAIN_TEXT, convertToBytes(value));
        }

        private static byte[] convertToBytes(String string) {
            try {
                return string.getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
// Be careful with ordering otherwise conversion exception can be inevitable
Retrofit retrofit = new Retrofit.Builder()
  .baseUrl("http://some.api")
  .addConverterFactory(StringConverterFactory.create());
  .addConverterFactory(GsonConverterFactory.create());
  .build();
  
RestApi restApi = retrofit.create(RestApi.class);
Call<com.squareup.okhttp.Response> call = restApi.authenticate("user", "pass", null);
com.squareup.okhttp.Response response = call.execute();
@Flaccuss
Copy link

Thanks bro.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment