java post请求代码
时间: 2023-11-25 08:06:40 浏览: 27
以下是一个使用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 HttpPostRequest {
public static void main(String[] args) throws Exception {
// 设置POST请求的URL地址和参数
String url = "http://example.com/api";
String param = "name=" + URLEncoder.encode("John", "UTF-8") + "&age=30";
// 创建一个URL对象
URL obj = new URL(url);
// 创建一个HttpURLConnection对象,用于发送POST请求
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
con.setRequestMethod("POST");
// 设置请求头
con.setRequestProperty("User-Agent", "Mozilla/5.0");
// 向连接中写入数据
con.setDoOutput(true);
con.getOutputStream().write(param.getBytes("UTF-8"));
// 发送请求并获取响应
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 输出响应结果
System.out.println(response.toString());
}
}
```
在上面的示例代码中,我们首先设置POST请求的URL地址和参数,然后创建一个HttpURLConnection对象,设置请求方法为POST,并向连接中写入数据。最后发送请求并获取响应,输出响应结果。