httpclient 添加Soap Action Header
时间: 2024-06-09 14:06:14 浏览: 12
在使用 HttpClient 发送 SOAP 请求时,需要在请求头中添加一个 SoapAction 头部,指定所调用的 SOAP 方法。可以使用 HttpClient 的 setHeader 方法来添加 SoapAction 头部,示例代码如下:
```java
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
public class SoapClient {
public static void main(String[] args) throws Exception {
String url = "http://example.com/soap";
String soapAction = "http://example.com/soap/HelloWorld";
// 创建 HttpClient 实例
HttpClient httpClient = HttpClientBuilder.create().build();
// 创建 HttpPost 请求
HttpPost httpPost = new HttpPost(url);
// 设置 SoapAction 头部
httpPost.setHeader(new BasicHeader("SOAPAction", soapAction));
// 设置请求体
String requestBody = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
" <soap:Body>\n" +
" <HelloWorld xmlns=\"http://example.com/soap\">\n" +
" <name>World</name>\n" +
" </HelloWorld>\n" +
" </soap:Body>\n" +
"</soap:Envelope>";
HttpEntity requestEntity = new StringEntity(requestBody, HTTP.UTF_8);
httpPost.setEntity(requestEntity);
// 发送请求并获取响应
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity responseEntity = httpResponse.getEntity();
String responseBody = EntityUtils.toString(responseEntity, HTTP.UTF_8);
// 打印响应内容
System.out.println(responseBody);
}
}
```
在上面的代码中,我们使用了 setHeader 方法来设置 SoapAction 头部,其参数为一个 BasicHeader 对象,其构造函数接收两个参数:头部名称和头部值。在发送请求时,我们将 HttpPost 对象传递给 HttpClient 的 execute 方法,并获取响应的实体内容。最后,我们把响应实体转换成字符串并打印出来。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)