Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Search Gists
Sign in Sign up

Instantly share code, notes, and snippets.

@plastiv
CreatedApril 22, 2015 08:04
    • Star(4)You must be signed in to star a gist
    • Fork(2)You must be signed in to fork a gist
    Save plastiv/08538a095d2d35acab05 to your computer and use it in GitHub Desktop.
    Retrofit multipart convertor
    @MultipartBody
    publicclassArticle {
    Stringauthor;
    Filephoto;
    }
    @Target(TYPE)
    @Retention(RUNTIME)
    public @interfaceMultipartBody {
    }
    publicclassMultipartConvertorimplementsConverter {
    privatefinalConverterdelegateConvertor;
    publicMultipartConvertor(ConvertergsonConverter) {
    this.delegateConvertor =gsonConverter;
    }
    @OverridepublicObjectfromBody(TypedInputbody,Typetype)throwsConversionException {
    returndelegateConvertor.fromBody(body,type);
    }
    @OverridepublicTypedOutputtoBody(Objectobject) {
    Class<?>rawType =object.getClass();
    if (rawType.isAnnotationPresent(MultipartBody.class)) {
    List<Field>fields =ReflectionUtil.getFields(rawType);
    MultipartTypedOutputmultipartTypedOutput =newMultipartTypedOutput();
    for (Fieldfield :fields) {
    if (field.getClass().equals(String.class)) {
    try {
    Stringvalue = (String)field.get(object);
    TypedStringtypedString =newTypedString(value);
    multipartTypedOutput.addPart(field.getName(),typedString);
    }catch (IllegalAccessExceptione) {
    // TODO: handle
    }
    }elseif (field.getClass().equals(File.class)) {
    try {
    Filevalue = (File)field.get(object);
    TypedFiletypedFile =newTypedFile("todo",value);
    multipartTypedOutput.addPart(field.getName(),typedFile);
    }catch (IllegalAccessExceptione) {
    // TODO: handle
    }
    }else {
    thrownewUnsupportedOperationException("Not implemented: " +field.getClass());
    }
    }
    returnmultipartTypedOutput;
    }
    returndelegateConvertor.toBody(object);
    }
    }
    publicinterfaceRetrofit {
    @POST("/api/v1/articles/")
    publicObservable<Response>createArticle(@BodyArticlearticle);
    }
    @johnjohndoe
    Copy link

    I link theStackoverflow question here.
    Interesting! Maybe@JakeWharton wants to include this inRetrofit. I createdthis issue.

    Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment

    [8]ページ先頭

    ©2009-2025 Movatter.jp