Skip to content

Instantly share code, notes, and snippets.

@wjch
Created January 22, 2017 10:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wjch/fe37434f1e212708bede8c8c74318d17 to your computer and use it in GitHub Desktop.
Save wjch/fe37434f1e212708bede8c8c74318d17 to your computer and use it in GitHub Desktop.
Retrofit方法,将数据转换成String类型的数据
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