PbootUtil.java 5.7 KB
package com.aigeo.util;

import okhttp3.*;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class PbootUtil {
    private static final String BASE_URL = "http://web.szcxybz.com/admin.php/content/";
    private static final String API_APP_ID = "admin";
    private static final String API_SECRET_KEY = "123456";
    private static final OkHttpClient httpClient = new OkHttpClient();
    private static final String MEDIA_TYPE_JSON = "application/json; charset=utf-8";
    private static final String MEDIA_TYPE_FORM = "application/x-www-form-urlencoded; charset=utf-8";

    /**
     * 通用API请求方法
     * @param url 请求路径
     * @param method 请求方法 (GET/POST)
     * @param params 请求参数
     * @return 响应结果
     */
    public static String apiRequest(String url, String method, Map<String, Object> params) throws IOException {
        // 获取当前时间戳
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);

        // 生成签名
        String signature = generateSignature(API_APP_ID, API_SECRET_KEY, timestamp);

        // 构造请求参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("appid", API_APP_ID);
        requestParams.put("timestamp", timestamp);
        requestParams.put("signature", signature);

        // 添加传入的参数
        if (params != null) {
            requestParams.putAll(params);
        }

        if ("POST".equalsIgnoreCase(method)) {
            return postRequest(url, requestParams);
        } else {
            return getRequest(url, requestParams);
        }
    }

    /**
     * 发送POST请求
     * @param url 请求路径
     * @param params 请求参数
     * @return 响应结果
     */
    private static String postRequest(String url, Map<String, Object> params) throws IOException {
        // 构建表单数据而不是JSON
        FormBody.Builder formBuilder = new FormBody.Builder();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            formBuilder.add(entry.getKey(), String.valueOf(entry.getValue()));
        }

        RequestBody body = formBuilder.build();

        Request request = new Request.Builder()
                .url(BASE_URL + url)
                .post(body)
                .addHeader("Content-Type", MEDIA_TYPE_FORM)
                .build();

        try (Response response = httpClient.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                throw new IOException("请求失败: " + response.code() + " " + response.message());
            }
        }
    }

    /**
     * 发送GET请求
     * @param url 请求路径
     * @param params 请求参数
     * @return 响应结果
     */
    private static String getRequest(String url, Map<String, Object> params) throws IOException {
        // 构建带参数的URL
        String fullUrl = buildUrlWithParams(BASE_URL + url, params);

        Request request = new Request.Builder()
                .url(fullUrl)
                .get()
                .addHeader("Content-Type", MEDIA_TYPE_JSON)
                .build();

        try (Response response = httpClient.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                throw new IOException("请求失败: " + response.code() + " " + response.message());
            }
        }
    }

    /**
     * 构建带查询参数的URL
     * @param baseUrl 基础URL
     * @param params 查询参数
     * @return 完整URL
     */
    private static String buildUrlWithParams(String baseUrl, Map<String, Object> params) {
        if (params == null || params.isEmpty()) {
            return baseUrl;
        }

        StringBuilder urlBuilder = new StringBuilder(baseUrl);
        urlBuilder.append("?");

        boolean first = true;
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            if (!first) {
                urlBuilder.append("&");
            }
            urlBuilder.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue());
            first = false;
        }

        return urlBuilder.toString();
    }

    /**
     * 生成PbootCMS API签名(双层MD5加密)
     * @param appid 应用ID
     * @param secret 密钥
     * @param timestamp 时间戳
     * @return 签名字符串
     */
    private static String generateSignature(String appid, String secret, String timestamp) {
        // 构造签名字符串: appid + secret + timestamp
        String sign = appid + secret + timestamp;

        // 双层MD5加密
        String firstMd5 = DigestUtils.md5Hex(sign);
        return DigestUtils.md5Hex(firstMd5);
    }

    // 使用示例
    //public static void main(String[] args) {
    //    try {
    //        // GET请求示例
    //        //String getResult = apiRequest("site", "GET", null);
    //        //System.out.println("GET结果: " + getResult);
    //
    //        // POST请求示例
    //        Map<String, Object> postParams = new HashMap<>();
    //        postParams.put("contacts", "测试文章标题");
    //        postParams.put("name", "nimhjcws");
    //        postParams.put("tel", "14523687549");
    //        postParams.put("mobile", "12345678914");
    //        postParams.put("content", ";lsdjfpolasndlwiojnkldoifdfnddfd");
    //
    //        String postResult = apiRequest("add", "POST", postParams);
    //        System.out.println("POST结果: " + postResult);
    //
    //    } catch (IOException e) {
    //        e.printStackTrace();
    //    }
    //}
}