HTTP 示例

本节通过一些示例总结了我们对 Spring 集成 HTTP 支持的介绍。

多部分 HTTP 请求 — RestTemplate(客户端)和 Http 入站网关(服务器)

此示例演示了使用 Spring 的 RestTemplate 发送多部分 HTTP 请求并在 Spring 集成 HTTP 入站适配器中接收它的简单性。我们创建一个 MultiValueMap 并使用多部分数据填充它。RestTemplate 通过将其转换为 MultipartHttpServletRequest 来处理其余部分(双关语)。此特定客户端发送包含公司名称和图像文件(公司徽标)的多部分 HTTP 请求。以下清单显示了示例

RestTemplate template = new RestTemplate();
String uri = "https://127.0.0.1:8080/multipart-http/inboundAdapter.htm";
Resource s2logo =
   new ClassPathResource("org/springframework/samples/multipart/spring09_logo.png");
MultiValueMap map = new LinkedMultiValueMap();
map.add("company", "SpringSource");
map.add("company-logo", s2logo);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(new MediaType("multipart", "form-data"));
HttpEntity request = new HttpEntity(map, headers);
ResponseEntity<?> httpResponse = template.exchange(uri, HttpMethod.POST, request, null);

对于客户端,这就是我们需要的全部。

在服务器端,我们有以下配置

<int-http:inbound-channel-adapter id="httpInboundAdapter"
    channel="receiveChannel"
    path="/inboundAdapter.htm"
    supported-methods="GET, POST"/>

<int:channel id="receiveChannel"/>

<int:service-activator input-channel="receiveChannel">
    <bean class="org.springframework.integration.samples.multipart.MultipartReceiver"/>
</int:service-activator>

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

“httpInboundAdapter”接收请求并将其转换为有效负载为 LinkedMultiValueMapMessage。然后,我们在“multipartReceiver”服务激活器中解析它,如下例所示

public void receive(LinkedMultiValueMap<String, Object> multipartRequest){
    System.out.println("### Successfully received multipart request ###");
    for (String elementName : multipartRequest.keySet()) {
        if (elementName.equals("company")){
            System.out.println("\t" + elementName + " - " +
                ((String[]) multipartRequest.getFirst("company"))[0]);
        }
        else if (elementName.equals("company-logo")){
            System.out.println("\t" + elementName + " - as UploadedMultipartFile: " +
                ((UploadedMultipartFile) multipartRequest
                    .getFirst("company-logo")).getOriginalFilename());
        }
    }
}

您应该看到以下输出

### Successfully received multipart request ###
   company - SpringSource
   company-logo - as UploadedMultipartFile: spring09_logo.png