java post请求
时间: 2023-06-28 12:14:29 浏览: 86
Java中发送POST请求的代码示例:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class PostExample {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("http://example.com/resource");
// 创建HttpURLConnection对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
conn.setRequestMethod("POST");
// 设置请求头
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 设置请求参数
String params = "param1=" + URLEncoder.encode("value1", "UTF-8") +
"¶m2=" + URLEncoder.encode("value2", "UTF-8");
conn.setDoOutput(true);
conn.getOutputStream().write(params.getBytes("UTF-8"));
// 发送请求
conn.connect();
// 读取响应
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
其中,`url`是请求的地址,`params`是请求参数,`Content-Type`是请求头,可以根据实际情况进行修改。
阅读全文