用java点击JButton 进行post请求
时间: 2023-05-11 10:05:18 浏览: 55
可以使用 Java 的 HttpURLConnection 类来进行 POST 请求。以下是一个示例代码:
```java
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
// ...
String url = "http://example.com/api";
String postData = "param1=value1¶m2=value2";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为 POST
con.setRequestMethod("POST");
// 设置请求头
con.setRequestProperty("User-Agent", "Mozilla/5.0");
// 启用输出
con.setDoOutput(true);
// 将 POST 数据写入请求体
OutputStream os = con.getOutputStream();
os.write(postData.getBytes());
os.flush();
os.close();
// 获取响应
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 输出响应
System.out.println(response.toString());
```
在这个示例中,我们使用 HttpURLConnection 类来发送 POST 请求。我们首先设置请求方法为 POST,然后设置请求头,启用输出,将 POST 数据写入请求体,发送请求并获取响应。最后,我们将响应输出到控制台。
相关推荐
![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_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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)