HttpClient post xml 并返回响应xml
时间: 2023-07-19 12:39:18 浏览: 57
好的,下面是Java代码示例:
```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.util.EntityUtils;
public class XmlHttpPostExample {
public static void main(String[] args) throws Exception {
String url = "http://example.com/api"; // 替换成实际的API地址
String xml = "<request><name>John</name></request>"; // 替换成实际的请求XML
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
// 设置请求头
httpPost.setHeader("Content-Type", "application/xml;charset=UTF-8");
// 设置请求体
StringEntity requestBody = new StringEntity(xml, "UTF-8");
httpPost.setEntity(requestBody);
// 发送请求并获取响应
HttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
// 将响应实体转换为字符串
String responseXml = EntityUtils.toString(responseEntity, "UTF-8");
System.out.println(responseXml);
}
}
}
```
在上面的示例中,我们使用 Apache HttpClient 发送一个 POST 请求,并将请求体设置为一个 XML 字符串。我们还设置了请求头来指定请求的内容类型为 XML。发送请求后,我们从响应实体中获取响应 XML 并将其打印出来。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)