发送xml格式报文怎么写?
时间: 2024-09-12 18:01:57 浏览: 30
java http 发送xml报文(java发送xml报文实例+参数)
在Apache HttpClient 4.5.14中,如果你想发送XML格式的报文(例如通过POST请求),你可以使用`HttpEntityEnclosingRequestBase`类,配合`MultipartEntityBuilder`构建一个`StringRequestEntity`,然后设置到`HttpPost`实例上。下面是一个示例:
```java
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class SendXmlHttpPost {
private static final CloseableHttpClient httpClient = HttpClients.createDefault();
public void sendXmlPost(String url, String xmlData) throws Exception {
// 创建HttpPost请求
HttpPost httpPost = new HttpPost(url);
// 构建XML数据部分
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("data", new StringBody(xmlData, ContentType.APPLICATION_XML));
// 设置请求体为XML多部分实体
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode >= 200 && statusCode < 300) {
System.out.println("Response status: " + statusCode);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
String responseBody = EntityUtils.toString(responseEntity, "UTF-8");
System.out.println("Response body: " + responseBody);
}
} else {
throw new RuntimeException("Failed to execute request, status code: " + statusCode);
}
}
}
// 关闭连接池
public void shutDown() throws IOException {
httpClient.close();
}
}
```
这里的`xmlData`是你想要发送的XML字符串。注意,你需要根据实际情况调整`contentType`和键值对。
阅读全文