Java POST 请求示例:发送 JSON 数据并插入数据库
以下是使用 Java 编写 POST 请求并将收到的 JSON 数据插入数据库的示例代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.json.JSONObject;
public class PostRequestExample {
public static void main(String[] args) throws Exception {
// 设置请求 URL 和 JSON 数据
String url = 'http://example.com/api/insertData';
JSONObject data = new JSONObject();
data.put('name', 'John');
data.put('age', 30);
// 发送 POST 请求
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod('POST');
con.setRequestProperty('Content-Type', 'application/json');
con.setDoOutput(true);
con.getOutputStream().write(data.toString().getBytes());
// 读取响应数据
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String response = '';
String line;
while ((line = in.readLine()) != null) {
response += line;
}
in.close();
// 解析 JSON 数据并插入数据库
JSONObject responseData = new JSONObject(response);
String name = responseData.getString('name');
int age = responseData.getInt('age');
insertData(name, age);
}
/**
* 插入数据到数据库
*/
private static void insertData(String name, int age) throws SQLException {
String url = 'jdbc:mysql://localhost:3306/mydatabase';
String username = 'root';
String password = 'password';
Connection conn = DriverManager.getConnection(url, username, password);
String sql = 'INSERT INTO users(name, age) VALUES (?, ?)';
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setInt(2, age);
pstmt.executeUpdate();
pstmt.close();
conn.close();
}
}
注意,上述代码中的 URL 仅为示例,需要替换为实际的 API 地址。同时,还需要根据实际情况修改数据库连接信息和 SQL 语句。
原文地址: https://www.cveoy.top/t/topic/nUgT 著作权归作者所有。请勿转载和采集!