怎么使用java代码编写四种请求,并操作mysql数据库

not image

在Java中,你可以使用`HttpURLConnection`或第三方库(如Apache HttpClient)来发送HTTP请求。以下是使用`HttpURLConnection`编写四种基本HTTP请求(GET、POST、PUT、DELETE)的示例代码,并结合MySQL数据库操作。 ### 1. 添加MySQL JDBC驱动依赖 首先,确保你已经将MySQL JDBC驱动添加到项目中。如果你使用的是Maven项目,可以在`pom.xml`中添加以下依赖: ```xml mysql mysql-connector-java 8.0.33 ``` ### 2. 编写HTTP请求和MySQL操作代码 ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class HttpAndMySQLExample { // MySQL数据库连接信息 private static final String DB_URL = "jdbc:mysql://localhost:3306/your_database"; private static final String DB_USER = "your_username"; private static final String DB_PASSWORD = "your_password"; public static void main(String[] args) { try { // 发送GET请求 sendGetRequest("https://jsonplaceholder.typicode.com/posts/1"); // 发送POST请求 sendPostRequest("https://jsonplaceholder.typicode.com/posts", "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}"); // 发送PUT请求 sendPutRequest("https://jsonplaceholder.typicode.com/posts/1", "{\"id\": 1, \"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}"); // 发送DELETE请求 sendDeleteRequest("https://jsonplaceholder.typicode.com/posts/1"); // 操作MySQL数据库 operateMySQL(); } catch (Exception e) { e.printStackTrace(); } } // 发送GET请求 private static void sendGetRequest(String url) throws Exception { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode(); System.out.println("GET Response Code: " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println("GET Response: " + response.toString()); } // 发送POST请求 private static void sendPostRequest(String url, String jsonInputString) throws Exception { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json; utf-8"); connection.setDoOutput(true); try (OutputStream os = connection.getOutputStream()) { byte[] input = jsonInputString.getBytes("utf-8"); os.write(input, 0, input.length); } int responseCode = connection.getResponseCode(); System.out.println("POST Response Code: " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")); StringBuilder response = new StringBuilder(); String responseLine; while ((responseLine = in.readLine()) != null) { response.append(responseLine.trim()); } System.out.println("POST Response: " + response.toString()); } // 发送PUT请求 private static void sendPutRequest(String url, String jsonInputString) throws Exception { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("PUT"); connection.setRequestProperty("Content-Type", "application/json; utf-8"); connection.setDoOutput(true); try (OutputStream os = connection.getOutputStream()) { byte[] input = jsonInputString.getBytes("utf-8"); os.write(input, 0, input.length); } int responseCode = connection.getResponseCode(); System.out.println("PUT Response Code: " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")); StringBuilder response = new StringBuilder(); String responseLine; while ((responseLine = in.readLine()) != null) { response.append(responseLine.trim()); } System.out.println("PUT Response: " + response.toString()); } // 发送DELETE请求 private static void sendDeleteRequest(String url) throws Exception { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("DELETE"); int responseCode = connection.getResponseCode(); System.out.println("DELETE Response Code: " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println("DELETE Response: " + response.toString()); } // 操作MySQL数据库 private static void operateMySQL() { try (Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) { // 查询数据 String query = "SELECT * FROM users"; PreparedStatement preparedStatement = connection.prepareStatement(query); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { System.out.println("User ID: " + resultSet.getInt("id") + ", Name: " + resultSet.getString("name")); } // 插入数据 String insertQuery = "INSERT INTO users (name, email) VALUES (?, ?)"; preparedStatement = connection.prepareStatement(insertQuery); preparedStatement.setString(1, "John Doe"); preparedStatement.setString(2, "john.doe@example.com"); preparedStatement.executeUpdate(); System.out.println("Data inserted successfully!"); // 更新数据 String updateQuery = "UPDATE users SET name = ? WHERE id = ?"; preparedStatement = connection.prepareStatement(updateQuery); preparedStatement.setString(1, "Jane Doe"); preparedStatement.setInt(2, 1); // 假设ID为1的用户存在 preparedStatement.executeUpdate(); System.out.println("Data updated successfully!"); // 删除数据 String deleteQuery = "DELETE FROM users WHERE id = ?"; preparedStatement = connection.prepareStatement(deleteQuery); preparedStatement.setInt(1, 1); // 假设ID为1的用户存在 preparedStatement.executeUpdate(); System.out.println("Data deleted successfully!"); } catch (SQLException e) { e.printStackTrace(); } } } ``` ### 3. 代码说明 - **HTTP请求部分**:使用`HttpURLConnection`发送GET、POST、PUT、DELETE请求,并处理响应。 - **MySQL操作部分**:使用JDBC连接MySQL数据库,执行查询、插入、更新和删除操作。 - **异常处理**:捕获并打印异常信息,确保程序不会因为异常而崩溃。 ### 4. 运行环境 - 确保MySQL数据库已启动,并且`your_database`、`your_username`、`your_password`等信息正确。 -

评论区:

评论:

请输入内容: