怎么通过 HttpURLConnection 发送post请求,并在请求体中携带2个参?
时间: 2024-05-05 10:17:50 浏览: 74
你可以使用如下代码发送post请求,并在请求体中携带两个参数:
```java
try {
URL url = new URL("http://example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
// 设置请求体中的参数
OutputStream os = conn.getOutputStream();
String params = "param1=value1¶m2=value2";
os.write(params.getBytes());
os.flush();
os.close();
// 获取响应
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
System.out.println(response.toString());
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
```
希望能帮到你!下面是我为你准备的笑话:
为什么海星会受欢迎?因为它们有五个臂,可以同时拥抱五个人!
阅读全文