无尘阁日记

无尘阁日记

使用Java将数据库中的数据通过API推送到微信公众号草稿箱的教程
2024-07-29

一、配置数据库

在Java中,通常使用JDBC来配置数据库连接。以下是一个示例:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConfig {
private static final String URL = "jdbc:mysql://localhost:3306/your_database_name";
private static final String USER = "your_username";
private static final String PASSWORD = "your_password";

public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASSWORD);
}
}

二、创建模型类

使用Java类来表示数据库表中的数据:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Article {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

private String title;
private String content;
private String author;
private String summary;
private String coverImage;

// Getters and setters
public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

public String getSummary() {
return summary;
}

public void setSummary(String summary) {
this.summary = summary;
}

public String getCoverImage() {
return coverImage;
}

public void setCoverImage(String coverImage) {
this.coverImage = coverImage;
}
}

三、实现微信公众号的API调用

使用HttpClient来发送HTTP请求:

import java.io.File;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class WechatService {
private static final String APP_ID = "your_wechat_app_id";
private static final String APP_SECRET = "your_wechat_app_secret";
private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
private static final String DRAFT_URL = "https://api.weixin.qq.com/cgi-bin/draft/add";
private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload";

private String accessToken;

public String getAccessToken() throws IOException {
if (this.accessToken != null) {
return this.accessToken;
}

try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet(TOKEN_URL + "?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
JsonObject jsonObject = JsonParser.parseString(responseString).getAsJsonObject();
this.accessToken = jsonObject.get("access_token").getAsString();
return this.accessToken;
}
}
}

public String uploadImage(String imagePath) throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(UPLOAD_URL + "?access_token=" + getAccessToken() + "&type=image");

File file = new File(imagePath);
HttpEntity entity = MultipartEntityBuilder.create()
.addBinaryBody("media", file, ContentType.DEFAULT_BINARY, file.getName())
.build();
           httpPost.setEntity(entity);

try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
HttpEntity responseEntity = response.getEntity();
String responseString = EntityUtils.toString(responseEntity);
JsonObject jsonObject = JsonParser.parseString(responseString).getAsJsonObject();
return jsonObject.get("media_id").getAsString();
}
}
}

public JsonObject pushArticleToDraft(Article article) throws IOException {
String thumbMediaId = uploadImage(article.getCoverImage());
JsonObject articleJson = new JsonObject();
       articleJson.addProperty("title", article.getTitle());
       articleJson.addProperty("thumb_media_id", thumbMediaId);
       articleJson.addProperty("author", article.getAuthor());
       articleJson.addProperty("digest", article.getSummary());
       articleJson.addProperty("content", article.getContent());
       articleJson.addProperty("content_source_url", "");
       articleJson.addProperty("need_open_comment", 1);
       articleJson.addProperty("only_fans_can_comment", 0);

JsonObject dataJson = new JsonObject();
       dataJson.add("articles", articleJson);

try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(DRAFT_URL + "?access_token=" + getAccessToken());
StringEntity entity = new StringEntity(dataJson.toString(), ContentType.APPLICATION_JSON);
           httpPost.setEntity(entity);

try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
HttpEntity responseEntity = response.getEntity();
String responseString = EntityUtils.toString(responseEntity);
return JsonParser.parseString(responseString).getAsJsonObject();
}
}
}
}

四、从数据库取出数据并推送文章到草稿箱

从数据库中读取文章数据并调用WechatService推送文章:

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class ArticleService {

   public List<Article> getAllArticles() {
       List<Article> articles = new ArrayList<>();
       String query = "SELECT * FROM articles";

       try (Connection connection = DatabaseConfig.getConnection();
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(query)) {

           while (resultSet.next()) {
               Article article = new Article();
               article.setId(resultSet.getInt("id"));
               article.setTitle(resultSet.getString("title"));
               article.setContent(resultSet.getString("content"));
               article.setAuthor(resultSet.getString("author"));
               article.setSummary(resultSet.getString("summary"));
               article.setCoverImage(resultSet.getString("cover_image"));
               articles.add(article);
           }
       } catch (Exception e) {
           e.printStackTrace();
       }

       return articles;
   }

   public static void main(String[] args) {
       ArticleService articleService = new ArticleService();
       WechatService wechatService = new WechatService();

       List<Article> articles = articleService.getAllArticles();

       for (Article article : articles) {
           try {
               JsonObject result = wechatService.pushArticleToDraft(article);
               System.out.println("Article pushed to draft: " + result.toString());
           } catch (Exception e) {
               System.err.println("Failed to push article: " + e.getMessage());
           }
       }
   }
}

五、验证和调试

启动Java应用,运行 `ArticleService.main` 方法,确保所有配置和调用都正确无误。

java_project.zip


发表评论: