java post json
时间: 2023-09-02 14:12:17 浏览: 74
java 实现通过 post 方式提交json参数操作
To make a POST request with JSON data in Java, you can use the HttpURLConnection class. Here is an example code snippet:
```
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.io.OutputStream;
public class JsonPostExample {
public static void main(String[] args) {
try {
// Create the URL and connection objects
URL url = new URL("http://example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
// Create the JSON data to be sent
String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
// Write the JSON data to the connection's output stream
OutputStream os = conn.getOutputStream();
os.write(json.getBytes(StandardCharsets.UTF_8));
os.flush();
os.close();
// Check the response code
int responseCode = conn.getResponseCode();
System.out.println("Response Code : " + responseCode);
// Read the response from the connection's input stream
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Print the response
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
In this example, we create a POST request to send JSON data to an API endpoint. We set the request method to POST and set the Content-Type and Accept headers to application/json. We also set the connection's output stream to write the JSON data to the request body.
After sending the request, we check the response code and read the response from the connection's input stream. We print the response to the console.
阅读全文