如何使用xml body调用REST api

时间:2011-11-10 05:45:41

标签: java xml rest

我有一个用于登录的REST api(https://localhost/server/api/login),它接受xml格式的参数,如下所示。

<?xml version="1.0" encoding="UTF-8" ?> 
<Request xmlns="http://www.xxxx.com/center/cbm/1.0.0">
  <Users>
    <User>
      <Type>userType</Type> 
      <Name>admin</Name> 
      <Password>password</Password> 
      <Captcha>On</Captcha> 
    </User>
   </Users>
 </Request>

如何使用Java调用它并接收响应。

1 个答案:

答案 0 :(得分:2)

您可以使用Apache HTTP Client 4.x执行HTTP POST请求:

String xmlString = "... your data ..."

HttpPost httpRequest = new HttpPost("https://localhost/server/api/login");
httpRequest.setEntity(new StringEntity(xmlString));

HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httpRequest, new BasicHttpContext());

if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK && httpResponse.getEntity() != null) {
  //handle response ok
} else {
  //handle error
}