Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
This repository was archived by the owner on Dec 31, 2024. It is now read-only.
/feign-formPublic archive

Open Feign form encoder

License

NotificationsYou must be signed in to change notification settings

OpenFeign/feign-form

Repository files navigation

IMPORTANT: the repository is inactive and was merged with the main feign project.

build_statusmaven_centralLicense

This module adds support for encodingapplication/x-www-form-urlencoded andmultipart/form-data forms.

Add dependency

Include the dependency to your app:

Maven:

<dependencies>  ...  <dependency>    <groupId>io.github.openfeign.form</groupId>    <artifactId>feign-form</artifactId>    <version>4.0.0</version>  </dependency>  ...</dependencies>

Gradle:

compile'io.github.openfeign.form:feign-form:4.0.0'

Requirements

Thefeign-form extension depend onOpenFeign and itsconcrete versions:

  • allfeign-form releases before3.5.0 works withOpenFeign9.* versions;
  • starting fromfeign-form's version3.5.0, the module works withOpenFeign10.1.0 versions and greater.

IMPORTANT: there is no backward compatibility and no any gurantee that thefeign-form's versions after3.5.0 work withOpenFeign before10.*.OpenFeign was refactored in 10th release, so the best approach - use the freshestOpenFeign andfeign-form versions.

Notes:

  • spring-cloud-openfeign usesOpenFeign9.* tillv2.0.3.RELEASE and uses10.* after. Anyway, the dependency already has suitablefeign-form version, seedependency pom, so you don't need to specify it separately;

  • spring-cloud-starter-feign is adeprecated dependency and it always uses theOpenFeign's9.* versions.

Usage

AddFormEncoder to yourFeign.Builder like so:

SomeApigithub =Feign.builder()                      .encoder(newFormEncoder())                      .target(SomeApi.class,"http://api.some.org");

Moreover, you can decorate the existing encoder, for example JsonEncoder like this:

SomeApigithub =Feign.builder()                      .encoder(newFormEncoder(newJacksonEncoder()))                      .target(SomeApi.class,"http://api.some.org");

And use them together:

interfaceSomeApi {@RequestLine("POST /json")@Headers("Content-Type: application/json")voidjson (Dtodto);@RequestLine("POST /form")@Headers("Content-Type: application/x-www-form-urlencoded")voidfrom (@Param("field1")Stringfield1,@Param("field2")String[]values);}

You can specify two types of encoding forms byContent-Type header.

application/x-www-form-urlencoded

interfaceSomeApi {@RequestLine("POST /authorization")@Headers("Content-Type: application/x-www-form-urlencoded")voidauthorization (@Param("email")Stringemail,@Param("password")Stringpassword);// Group all parameters within a POJO@RequestLine("POST /user")@Headers("Content-Type: application/x-www-form-urlencoded")voidaddUser (Useruser);classUser {Integerid;Stringname;  }}

multipart/form-data

interfaceSomeApi {// File parameter@RequestLine("POST /send_photo")@Headers("Content-Type: multipart/form-data")voidsendPhoto (@Param("is_public")BooleanisPublic,@Param("photo")Filephoto);// byte[] parameter@RequestLine("POST /send_photo")@Headers("Content-Type: multipart/form-data")voidsendPhoto (@Param("is_public")BooleanisPublic,@Param("photo")byte[]photo);// FormData parameter@RequestLine("POST /send_photo")@Headers("Content-Type: multipart/form-data")voidsendPhoto (@Param("is_public")BooleanisPublic,@Param("photo")FormDataphoto);// Group all parameters within a POJO@RequestLine("POST /send_photo")@Headers("Content-Type: multipart/form-data")voidsendPhoto (MyPojopojo);classMyPojo {@FormProperty("is_public")BooleanisPublic;Filephoto;  }}

In the example above, thesendPhoto method uses thephoto parameter using three different supported types.

  • File will use the File's extension to detect theContent-Type;
  • byte[] will useapplication/octet-stream asContent-Type;
  • FormData will use theFormData'sContent-Type andfileName;
  • Client's custom POJO for grouping parameters (including types above).

FormData is custom object that wraps abyte[] and defines aContent-Type andfileName like this:

FormDataformData =newFormData("image/png","filename.png",myDataAsByteArray);someApi.sendPhoto(true,formData);

Spring MultipartFile and Spring Cloud Netflix @FeignClient support

You can also use Form Encoder with SpringMultipartFile and@FeignClient.

Include the dependencies to your project's pom.xml file:

<dependencies>  <dependency>    <groupId>io.github.openfeign.form</groupId>    <artifactId>feign-form</artifactId>    <version>4.0.0</version>  </dependency>  <dependency>    <groupId>io.github.openfeign.form</groupId>    <artifactId>feign-form-spring</artifactId>    <version>4.0.0</version>  </dependency></dependencies>
@FeignClient(name ="file-upload-service",configuration =FileUploadServiceClient.MultipartSupportConfig.class)publicinterfaceFileUploadServiceClientextendsIFileUploadServiceClient {publicclassMultipartSupportConfig {@AutowiredprivateObjectFactory<HttpMessageConverters>messageConverters;@BeanpublicEncoderfeignFormEncoder () {returnnewSpringFormEncoder(newSpringEncoder(messageConverters));    }  }}

Or, if you don't need Spring's standard encoder:

@FeignClient(name ="file-upload-service",configuration =FileUploadServiceClient.MultipartSupportConfig.class)publicinterfaceFileUploadServiceClientextendsIFileUploadServiceClient {publicclassMultipartSupportConfig {@BeanpublicEncoderfeignFormEncoder () {returnnewSpringFormEncoder();    }  }}

Thanks totf-haotri-pham for his feature, which makes use of Apache commons-fileupload library, which handles the parsing of the multipart response. The body data parts are held as byte arrays in memory.

To use this feature, include SpringManyMultipartFilesReader in the list of message converters for the Decoder and have the Feign client return an array of MultipartFile:

@FeignClient(name ="${feign.name}",url ="${feign.url}"configuration =DownloadClient.ClientConfiguration.class)publicinterfaceDownloadClient {@RequestMapping("/multipart/download/{fileId}")MultipartFile[]download(@PathVariable("fileId")StringfileId);classClientConfiguration {@AutowiredprivateObjectFactory<HttpMessageConverters>messageConverters;@BeanpublicDecoderfeignDecoder () {List<HttpMessageConverter<?>>springConverters =messageConverters.getObject().getConverters();List<HttpMessageConverter<?>>decoderConverters =newArrayList<HttpMessageConverter<?>>(springConverters.size() +1);decoderConverters.addAll(springConverters);decoderConverters.add(newSpringManyMultipartFilesReader(4096));HttpMessageConvertershttpMessageConverters =newHttpMessageConverters(decoderConverters);returnnewSpringDecoder(newObjectFactory<HttpMessageConverters>() {@OverridepublicHttpMessageConvertersgetObject() {returnhttpMessageConverters;        }      });    }  }}

[8]ページ先頭

©2009-2025 Movatter.jp