如何使用Spring RestTemplate发送XML POST请求?

mem*_*und 13 java xml spring

是否可以发送XML POST请求spring,例如RestTemplate

我想将以下xml发送到网址 localhost:8080/xml/availability

<AvailReq>
  <hotelid>123</hotelid>
</AvailReq>
Run Code Online (Sandbox Code Playgroud)

我还想动态地在每个请求上添加自定义http标头(!).

我怎么能用弹簧实现这个目标?

Ali*_*ani 31

首先,定义HTTP标题,如下所示:

HttpHeaders headers = new HttpHeaders();
headers.add("header_name", "header_value");
Run Code Online (Sandbox Code Playgroud)

您可以HTTP使用此方法设置任何标头.对于众所周知的标题,您可以使用预定义的方法.例如,为了设置Content-Type标题:

headers.setContentType(MediaType.APPLICATION_XML);
Run Code Online (Sandbox Code Playgroud)

然后定义一个HttpEntityRequestEntity准备您的请求对象:

HttpEntity<String> request = new HttpEntity<String>(body, headers);
Run Code Online (Sandbox Code Playgroud)

如果您以某种方式访问​​该XML字符串,则可以使用HttpEntity<String>.否则,您可以定义与之对应的POJO XML.最后使用postFor...方法发送请求:

ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8080/xml/availability", request, String.class);
Run Code Online (Sandbox Code Playgroud)

在这里,我正在POSThttp://localhost:8080/xml/availability端点发送请求并将HTTP响应主体转换为String.

注意,在上面的例子中new HttpEntity<String>(...)可以用JDK7及更高版本替换 new HttpEntity<>(...).

  • 使用您的“JAXB”类,例如“SomeClass”,而不是“String”。事实上,它是“HttpEntity&lt;SomeClass&gt; request = ...”。 (2认同)
  • “Jaxb2RootElementHttpMessageConverter”会将您的“JAXB”类转换为“XML”。它应该默认注册。如果由于某种原因未注册,请手动注册。 (2认同)

Sam*_*Sam 8

例如,在下面找到使用 RestTemplate 将 XML 交换为 String 并接收响应的示例:

String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><AvailReq><hotelid>123</hotelid></AvailReq>";

    RestTemplate restTemplate =  new RestTemplate();
    //Create a list for the message converters
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
    //Add the String Message converter
    messageConverters.add(new StringHttpMessageConverter());
    //Add the message converters to the restTemplate
    restTemplate.setMessageConverters(messageConverters);


    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_XML);
    HttpEntity<String> request = new HttpEntity<String>(xmlString, headers);

    final ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8080/xml/availability", request, String.class);
Run Code Online (Sandbox Code Playgroud)


Kam*_*kol 5

RestTemplate下面是如何使用交换 XML 文档并接收 HTML 响应的完整示例:

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.header;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;

import org.junit.Test;
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.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class XmlTest {

    @Test
    public void test() throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
        String htmlString = "<p>response</p>";
        String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><AvailReq><hotelid>123</hotelid></AvailReq>";

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(xmlString)));

        mockServer.expect(requestTo("http://localhost:8080/xml/availability"))
                .andExpect(method(HttpMethod.POST))
                .andExpect(content().string(is(xmlString)))
                .andExpect(header("header", "value"))
                .andRespond(withSuccess("<p>response</p>", MediaType.TEXT_HTML));

        HttpHeaders headers = new HttpHeaders();
        headers.add("header", "value");
        HttpEntity<Document> request = new HttpEntity<>(document, headers);

        final ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8080/xml/availability", request, String.class);

        assertThat(response.getBody(), is(htmlString));
        mockServer.verify();
    }
}
Run Code Online (Sandbox Code Playgroud)