-
-
Save weikipeng/6309dc3861ac3e12d931 to your computer and use it in GitHub Desktop.
Retrofit 2.0 converter for plain/text requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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