java 使用HttpClient实现、POST表单发送/接收XML格式的报文,POST参数名为req的示例代码
时间: 2024-03-15 15:46:14 浏览: 143
Java使用HttpClient实现Post请求实例
5星 · 资源好评率100%
以下是Java使用HttpClient实现POST表单发送/接收XML格式的报文,POST参数名为req的示例代码:
```
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpClientExample {
public static void main(String[] args) throws IOException {
String url = "http://example.com/api";
String xml = "<xml><name>John</name><age>30</age></xml>";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(xml, ContentType.APPLICATION_XML);
httpPost.setEntity(entity);
httpPost.setHeader("Content-type", "application/xml");
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
HttpEntity responseEntity = response.getEntity();
String responseString = EntityUtils.toString(responseEntity, "UTF-8");
System.out.println(responseString);
} finally {
response.close();
}
}
}
```
说明:
- `url`:要访问的URL地址。
- `xml`:要发送的XML格式的报文。
- `httpClient`:创建一个默认的HttpClient实例。
- `httpPost`:创建一个HttpPost实例,并将URL地址设置为请求的目标地址。
- `entity`:将XML报文封装为一个StringEntity对象,并设置内容类型为`application/xml`。
- `httpPost.setEntity(entity)`:将封装好的XML报文设置为HTTP POST请求的主体部分。
- `httpPost.setHeader("Content-type", "application/xml")`:设置请求头部的内容类型为`application/xml`。
- `response`:执行HTTP POST请求,并返回一个CloseableHttpResponse实例。
- `responseEntity`:从响应中获取响应主体。
- `responseString`:将响应主体转换为字符串格式。
- `response.close()`:关闭响应实例。
阅读全文