java post请求代码
时间: 2024-05-14 13:13:23 浏览: 20
java发送http/https请求(get/post)代码
4星 · 用户满意度95%
Sure, here's an example of how to make a POST request in Java:
```
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PostRequestExample {
public static void main(String[] args) throws Exception {
URL url = new URL("http://example.com/api/post");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
String data = "{ \"name\": \"John\", \"age\": 30 }";
OutputStream outputStream = connection.getOutputStream();
outputStream.write(data.getBytes());
outputStream.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = "";
String line;
while ((line = reader.readLine()) != null) {
response += line;
}
reader.close();
connection.disconnect();
System.out.println("Response: " + response);
}
}
```
This example sends a JSON payload to the URL `http://example.com/api/post` using a POST request. The payload is `{ "name": "John", "age": 30 }` and the response from the server is printed to the console.
阅读全文