需要jar包:
commons-logging-1.0.4.jar
httpclient-4.3.2.jar
httpcore-4.3.2.jar
测试:
package http;
public class TestSoap {
public static void main(String[] args) {
String soapXml="<?xml version=\"1.0\" encoding=\"utf-16\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
" <soap:Body>" +
" <execute xmlns=\"webservices.wst.weaver.com.cn\">" +
" <in0>wer</in0>" +
" <in1>2</in1>" +
" </execute>" +
" </soap:Body>" +
"</soap:Envelope>";
String result=HttpToSoap.doPostSoap("http://127.0.0.1:8087//services/WebServicesTest", soapXml, "", HttpToSoap.soap);
System.out.println(result);
}
}
代码:
package http;
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class HttpToSoap {
static int socketTimeout = 10000;// 请求超时时间
static int connectTimeout = 10000;// 传输超时时间
static final String soap = "text/xml;charset=UTF-8";
static final String soap11 = "application/soap+xml;charset=UTF-8";
/**
* 同步HttpPost请求发送SOAP格式的消息
*
* @param webServiceURL
* WebService接口地址
* @param soapXml
* 消息体
* @param soapAction
* soapAction
* @param soapType
* soap版本
* @return
*/
public static String doPostSoap(String webServiceURL, String soapXml,
String soapAction, String soapType) {
// 创建HttpClient
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
// 创建Post请求
HttpPost httpPost = new HttpPost(webServiceURL);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(socketTimeout)
.setConnectTimeout(connectTimeout).build();
httpPost.setConfig(requestConfig);
// 设置Post请求报文头部
httpPost.setHeader("Content-Type", soapType);
httpPost.setHeader("SOAPAction", soapAction);
// 添加报文内容
StringEntity data = new StringEntity(soapXml, Charset.forName("UTF-8"));
httpPost.setEntity(data);
try {
// 执行请求获取返回报文
CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
// 打印响应内容
return EntityUtils.toString(httpEntity, "UTF-8");
}
// 释放资源
closeableHttpClient.close();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}