java post请求带body参数
时间: 2024-09-20 08:03:26 浏览: 36
在Java中发送POST请求带有body参数,通常会使用`HttpURLConnection`或者更现代的库如`org.apache.httpcomponents.client5`或`okhttp`。这里是一个基本的例子使用`HttpURLConnection`:
```java
URL url = new URL("http://example.com/api/endpoint");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
try (OutputStream os = connection.getOutputStream()) {
String requestBody = "key1=value1&key2=value2"; // JSON or form data format
byte[] requestBodyBytes = requestBody.getBytes(StandardCharsets.UTF_8);
os.write(requestBodyBytes);
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} else {
System.err.println("Failed : HTTP error code : " + responseCode);
}
} catch (IOException e) {
e.printStackTrace();
}
```
这里的关键是设置`setDoOutput(true)`来启用输出流,并通过`OutputStream`写入请求体。如果是JSON数据,可能还需要添加适当的Content-Type头。
阅读全文