如何Servlet中用post发送请求
时间: 2024-06-09 14:06:10 浏览: 166
dxServlet.java处理Http Post的表单请求xml
4星 · 用户满意度95%
在Servlet中发送POST请求可以使用以下步骤:
1. 创建一个URL对象,指定请求的目标地址。
```
URL url = new URL("http://example.com/path/to/target");
```
2. 打开URL连接并设置请求方法为POST。
```
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
```
3. 设置请求头信息(可选)。
```
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
```
4. 设置请求体内容(如果有)。
```
String requestBody = "param1=value1¶m2=value2";
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(requestBody.getBytes());
outputStream.flush();
outputStream.close();
```
5. 获取响应结果。
```
int responseCode = connection.getResponseCode();
String responseBody = "";
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
responseBody += line;
}
reader.close();
inputStream.close();
}
```
完整的示例代码如下:
```
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String targetUrl = "http://example.com/path/to/target";
String requestBody = "param1=value1¶m2=value2";
URL url = new URL(targetUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(requestBody.getBytes());
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
String responseBody = "";
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
responseBody += line;
}
reader.close();
inputStream.close();
}
}
```
阅读全文