使用Java发送post请求
时间: 2024-06-09 10:08:18 浏览: 135
可以使用 Java 的 HttpURLConnection 类来发送 POST 请求。以下是一个简单的示例代码:
```java
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PostRequestExample {
public static void main(String[] args) throws Exception {
URL url = new URL("http://example.com/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
String data = "param1=value1¶m2=value2";
OutputStream outputStream = connection.getOutputStream();
outputStream.write(data.getBytes());
outputStream.flush();
outputStream.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
System.out.println(response.toString());
}
}
```
在这个示例中,我们首先创建一个 URL 对象来指定 POST 请求的目标地址。然后,我们使用 HttpURLConnection 类的实例来设置请求方法为 POST 并启用输出。接下来,我们将请求参数编码为字符串,并将其作为字节数组写入连接的输出流中。最后,我们读取响应并将其存储在 StringBuilder 对象中。
阅读全文