Created
January 22, 2017 10:04
-
-
Save wjch/fe37434f1e212708bede8c8c74318d17 to your computer and use it in GitHub Desktop.
Retrofit方法,将数据转换成String类型的数据
This file contains 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.lang.annotation.Annotation; | |
import java.lang.reflect.Type; | |
import retrofit.Converter; | |
public class ToStringConverterFactory extends Converter.Factory { | |
//定义媒体类型 | |
private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain"); | |
/** | |
* 创建一个转换器,将HTTP response body转换成对应的媒体Type(上面定义的是text/plain,即文本类型)。 | |
* 如果装换不了的话会返回空。 | |
*/ | |
@Override | |
public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) { | |
if (String.class.equals(type)) { | |
return new Converter<ResponseBody, String>() { | |
@Override | |
public String convert(ResponseBody value) throws IOException { | |
return value.string(); | |
} | |
}; | |
} | |
return null; | |
} | |
/** | |
* * 创建一个转换器,将HTTP request body转换成对应的媒体Type(上面定义的是text/plain,即文本类型)。 | |
* 如果装换不了的话会返回空。 | |
*/ | |
@Override | |
public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) { | |
if (String.class.equals(type)) { | |
return new Converter<String, RequestBody>() { | |
@Override | |
public RequestBody convert(String value) throws IOException { | |
return RequestBody.create(MEDIA_TYPE, value); | |
} | |
}; | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment