简体   繁体   中英

How to POST XML string using RestTemplate

I have the following scenario. I have an XML file:

query-users.xml

<?xml version="1.0"?>
<q:query xmlns:q="http://prism.evolveum.com/xml/ns/public/query-3">
</q:query>

When executing the curl commend:

curl.exe --user administrator:5ecr3t -H "Content-Type: application/xml" -X POST http://localhost:8080/midpoint/ws/rest/users/search -d @C:\Users\user\query-users.xml

I get the desired response in XML. I am trying to do the same POST request using RestTemplate from JAVA code:

try{    
    StringBuilder builder = new StringBuilder();
    builder.append("http://localhost:8080/midpoint/ws/rest/users/search");
    builder.append("?query=");
    builder.append(URLEncoder.encode("<?xml version=\"1.0\"?><q:query xmlns:q=\"http://prism.evolveum.com/xml/ns/public/query-3\"></q:query>"));

    URI uri = URI.create(builder.toString());

    restOperations.postForEntity(uri, new HttpEntity<String>(createHeaders("username", "pass")), String.class);
    logger.info(response);
    }catch(Exception e){
        logger.info(e.getMessage());
    }
}

I get Internal Servel Error . There is something that I am doing wrong passing the XML string to the POST request with RestTemplate , but I am not figuring out what it is.

Is there a way how to solve this?

Thanks

Your curl invocation and RestTemplate call are not equivalent. In first one you pass your xml as aa body of HTTP Request (this is what -d option does). In your RestTemplate you assign your xml to query and consequently HTTP Request has no payload and your data is encoded in URL.

If you want to pass your xml as a HTTP Body, you should use different HttpEntity constuctor: http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/HttpEntity.html#HttpEntity-T-org.springframework.util.MultiValueMap-

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM