Skip to content

Instantly share code, notes, and snippets.

@weikipeng
Forked from tomkoptel/RestApi.md
Last active September 6, 2015 05:14
Show Gist options
  • Select an option

  • Save weikipeng/6309dc3861ac3e12d931 to your computer and use it in GitHub Desktop.

Select an option

Save weikipeng/6309dc3861ac3e12d931 to your computer and use it in GitHub Desktop.
Retrofit 2.0 converter for plain/text requests
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.ResponseBody;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import retrofit.Converter;
final class StringConverterFactory implements Converter.Factory {
private StringConverterFactory() {}
public static StringConverterFactory create() {
return new StringConverterFactory();
}
@Override
public Converter<String> get(Type type) {
return new StringConverter();
}
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);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment