Skip to content

Instantly share code, notes, and snippets.

@flyfire
Forked from plastiv/Article.java
Created July 13, 2023 03:01
Show Gist options
  • Save flyfire/8719cd56747ea1824b5743e1cf9ba618 to your computer and use it in GitHub Desktop.
Save flyfire/8719cd56747ea1824b5743e1cf9ba618 to your computer and use it in GitHub Desktop.
Retrofit multipart convertor
@MultipartBody
public class Article {
String author;
File photo;
}
@Target(TYPE)
@Retention(RUNTIME)
public @interface MultipartBody {
}
public class MultipartConvertor implements Converter {
private final Converter delegateConvertor;
public MultipartConvertor(Converter gsonConverter) {
this.delegateConvertor = gsonConverter;
}
@Override public Object fromBody(TypedInput body, Type type) throws ConversionException {
return delegateConvertor.fromBody(body, type);
}
@Override public TypedOutput toBody(Object object) {
Class<?> rawType = object.getClass();
if (rawType.isAnnotationPresent(MultipartBody.class)) {
List<Field> fields = ReflectionUtil.getFields(rawType);
MultipartTypedOutput multipartTypedOutput = new MultipartTypedOutput();
for (Field field : fields) {
if (field.getClass().equals(String.class)) {
try {
String value = (String) field.get(object);
TypedString typedString = new TypedString(value);
multipartTypedOutput.addPart(field.getName(), typedString);
} catch (IllegalAccessException e) {
// TODO: handle
}
} else if (field.getClass().equals(File.class)) {
try {
File value = (File) field.get(object);
TypedFile typedFile = new TypedFile("todo", value);
multipartTypedOutput.addPart(field.getName(), typedFile);
} catch (IllegalAccessException e) {
// TODO: handle
}
}else {
throw new UnsupportedOperationException("Not implemented: " + field.getClass());
}
}
return multipartTypedOutput;
}
return delegateConvertor.toBody(object);
}
}
public interface Retrofit {
@POST("/api/v1/articles/")
public Observable<Response> createArticle(@Body Article article);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment