使用jersey客户端消耗spring REST api

时间:2017-11-29 16:31:19

标签: java spring rest jersey

我有一个用于上传多个文件的spring REST API。签名是

@RequestMapping(value = "uploadFiles", method = { RequestMethod.POST })
@ResponseBody
public CustomObject uploadFiles(@RequestParam("files") List<MultipartFile> uploads)

如何使用泽西客户端消费?我想将File或InputStream转换为MultiPartFile,并能够将其发送到此端点。

1 个答案:

答案 0 :(得分:0)

使用RestTemplate的示例

import java.io.File;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

public class Test {

            /**
            * @param args
            */
            public static void main(String[] args) {

                            try {
                                           File file1 = new File("/Users/file1");
                                            FileSystemResource fileSystemResource1 = new FileSystemResource(file1);

                                            File file2 = new File("/Users/file2");
                                            FileSystemResource fileSystemResource2 = new FileSystemResource(file2);

                                            RestTemplate restTemplate = new RestTemplate();

                                            HttpHeaders partHeaders = new HttpHeaders();
                                            partHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);


                                            MultiValueMap<String, Object> data = new LinkedMultiValueMap<>();
                                            data.add("files", fileSystemResource1);
                                             data.add("files", fileSystemResource2);

                                            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(data, partHeaders);

                                            ResponseEntity<String> response = restTemplate.exchange(
                                                                            endpoint, HttpMethod.POST,
                                                                            requestEntity, String.class);

                                            System.out.println(response.getBody() + " - " + response.getStatusCode());
                            } catch (Exception e) {
                                            e.printStackTrace();
                            }
            }

}