1 需求
在项目开发中需要调用webservice接口,接口的请求参数为xml格式,接口的响应结果也为xml格式。
2 引入pom依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
3 核心代码
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.CloseableHttpClient;
private String invokeInvoice(JSONObject params, Station station) {
String url = "https://test.com/open/services/test?wsdl";
String xml = getSoapEnvXml(params, station);
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
httpPost.setEntity(new StringEntity(xml));
HttpResponse response = httpClient.execute(httpPost);
String responseXml = EntityUtils.toString(response.getEntity());
return responseXml.replace("<", "<").replace(">", ">").replace("&", "&").replace("'", "'").replace(""", "\"");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}