java http post请求代码
时间: 2023-09-12 22:03:21 浏览: 49
以下是使用Java进行HTTP POST请求的示例代码:
```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class HttpPostExample {
public static void main(String[] args) {
try {
// 设置请求URL和请求参数
String url = "http://example.com/api";
String param = "name=" + URLEncoder.encode("张三", "UTF-8") + "&age=18";
// 创建URL对象和HttpURLConnection对象
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
con.setRequestMethod("POST");
//设置请求头信息
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// 启用输出流
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());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
上述代码使用了`HttpURLConnection`类来进行POST请求,其中需要设置请求URL、请求参数、请求方法以及请求头信息。在发送请求时,需要启用输出流,并将请求参数写入输出流中。最后,将输出流中的响应结果读取并打印。