代码示例

各种编程语言的完整代码示例和最佳实践

本页面提供了各种编程语言调用小红书内容发布 API 的详细代码示例。 所有示例都包含了错误处理、重试机制等最佳实践,可以直接在你的项目中使用。

错误处理

始终检查 API 响应中的 success 字段,并适当处理错误情况

重试机制

对于临时性错误(如网络问题),建议实现重试机制

资源 URL 建议

使用 HTTPS 协议的 URL,确保图片和视频资源可公开访问

内容优化

标题简洁明了,内容丰富有趣,图片清晰美观

编程语言示例

JavaScript
const axios = require('axios');

// 配置信息
const API_BASE_URL = 'https://www.myaibot.vip';
const API_KEY = 'your_api_key_here';

// 创建 HTTP 客户端
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 发布图文内容
async function publishImageNote(title, content, images) {
  try {
    const response = await apiClient.post('/api/rednote/publish', {
      api_key: API_KEY,
      type: 'normal',
      title: title,
      content: content,
      images: images
    });
    
    console.log('发布成功:', response.data);
    return response.data;
  } catch (error) {
    console.error('发布失败:', error.response?.data || error.message);
    throw error;
  }
}

// 发布视频内容
async function publishVideoNote(title, content, videoUrl, coverUrl) {
  try {
    const response = await apiClient.post('/api/rednote/publish', {
      api_key: API_KEY,
      type: 'video',
      title: title,
      content: content,
      video: videoUrl,
      cover: coverUrl
    });
    
    console.log('发布成功:', response.data);
    return response.data;
  } catch (error) {
    console.error('发布失败:', error.response?.data || error.message);
    throw error;
  }
}

// 使用示例
async function main() {
  try {
    // 发布图文
    const imageResult = await publishImageNote(
      '美食分享',
      '今天做了超好吃的蛋糕\n#美食 #烘焙',
      [
        'https://picsum.photos/400/400?random=1',
        'https://picsum.photos/400/400?random=2'
      ]
    );

    console.log('图文二维码:', imageResult.data.qrcode);

    // 发布视频
    const videoResult = await publishVideoNote(
      '旅行日记',
      '美丽的海边风景\n#旅行 #海景',
      'https://rednote-publish.oss-cn-hangzhou.aliyuncs.com/public/02-AI-NM.mp4',
      'https://picsum.photos/400/400?random=99'
    );
    
    console.log('视频二维码:', videoResult.data.qrcode);
    
  } catch (error) {
    console.error('操作失败:', error);
  }
}

main();
Python
import requests
import json
import time
from typing import List, Optional, Dict, Any

class XiaohongshuAPI:
    def __init__(self, api_key: str, base_url: str = 'https://www.myaibot.vip'):
        self.api_key = api_key
        self.base_url = base_url
        self.session = requests.Session()
        self.session.headers.update({
            'Content-Type': 'application/json'
        })
    
    def _request_with_retry(self, method: str, endpoint: str, data: Dict[Any, Any] = None, 
                           max_retries: int = 3, delay: float = 1.0) -> Dict[Any, Any]:
        """带重试机制的请求方法"""
        url = f"{self.base_url}{endpoint}"
        
        for attempt in range(max_retries):
            try:
                response = self.session.request(method, url, json=data)
                
                if response.status_code == 200:
                    return response.json()
                elif response.status_code in [500, 502, 503, 504, 429]:
                    # 服务器错误或限流,可以重试
                    if attempt < max_retries - 1:
                        print(f"请求失败,{delay * (attempt + 1)}秒后重试... (状态码: {response.status_code})")
                        time.sleep(delay * (attempt + 1))
                        continue
                
                # 处理其他错误
                self._handle_error_response(response)
                
            except requests.exceptions.RequestException as e:
                if attempt < max_retries - 1:
                    print(f"网络错误,{delay * (attempt + 1)}秒后重试: {e}")
                    time.sleep(delay * (attempt + 1))
                    continue
                else:
                    raise Exception(f"网络请求失败: {e}")
        
        raise Exception(f"请求失败,已重试 {max_retries} 次")
    
    def _handle_error_response(self, response: requests.Response):
        """处理错误响应"""
        try:
            error_data = response.json()
            error_message = error_data.get('error', {}).get('message', '未知错误')
        except:
            error_message = response.text or '未知错误'
        
        status_code = response.status_code
        if status_code == 401:
            raise Exception('API Key 无效或已过期')
        elif status_code == 402:
            raise Exception('调用次数不足,请充值')
        elif status_code == 400:
            raise Exception(f'参数错误: {error_message}')
        elif status_code == 429:
            raise Exception('请求频率过高,请稍后重试')
        else:
            raise Exception(f'请求失败 ({status_code}): {error_message}')
    
    def publish_image_note(self, title: str, content: str, images: List[str]) -> Dict[Any, Any]:
        """发布图文笔记"""
        data = {
            'api_key': self.api_key,
            'type': 'normal',
            'title': title,
            'content': content,
            'images': images
        }
        
        return self._request_with_retry('POST', '/api/rednote/publish', data)
    
    def publish_video_note(self, title: str, content: str, video: str, 
                          cover: Optional[str] = None) -> Dict[Any, Any]:
        """发布视频笔记"""
        data = {
            'api_key': self.api_key,
            'type': 'video',
            'title': title,
            'content': content,
            'video': video
        }
        
        if cover:
            data['cover'] = cover
        
        return self._request_with_retry('POST', '/api/rednote/publish', data)

# 使用示例
def main():
    # 初始化API客户端
    api = XiaohongshuAPI('your_api_key_here')
    
    try:
        # 发布图文笔记
        image_result = api.publish_image_note(
            title='美食分享',
            content='今天做了超好吃的蛋糕\n#美食 #烘焙',
            images=[
                'https://picsum.photos/400/400?random=1',
                'https://picsum.photos/400/400?random=2'
            ]
        )

        print('图文笔记发布成功:')
        print(f"ID: {image_result['data']['id']}")
        print(f"分享链接: {image_result['data']['url']}")
        print(f"二维码: {image_result['data']['qrcode']}")

        # 发布视频笔记
        video_result = api.publish_video_note(
            title='旅行日记',
            content='美丽的海边风景\n#旅行 #海景',
            video='https://rednote-publish.oss-cn-hangzhou.aliyuncs.com/public/02-AI-NM.mp4',
            cover='https://picsum.photos/400/400?random=99'
        )
        
        print('\n视频笔记发布成功:')
        print(f"ID: {video_result['data']['id']}")
        print(f"分享链接: {video_result['data']['url']}")
        print(f"二维码: {video_result['data']['qrcode']}")
        
    except Exception as e:
        print(f'发布失败: {e}')

if __name__ == '__main__':
    main()
PHP
<?php

class XiaohongshuAPI {
    private $apiKey;
    private $baseUrl;
    
    public function __construct($apiKey, $baseUrl = 'https://www.myaibot.vip') {
        $this->apiKey = $apiKey;
        $this->baseUrl = $baseUrl;
    }
    
    /**
     * 发送HTTP请求
     */
    private function sendRequest($method, $endpoint, $data = null, $maxRetries = 3) {
        $url = $this->baseUrl . $endpoint;
        $headers = [
            'Content-Type: application/json'
        ];
        
        for ($attempt = 1; $attempt <= $maxRetries; $attempt++) {
            $ch = curl_init();
            
            curl_setopt_array($ch, [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_SSL_VERIFYPEER => true
            ]);
            
            if ($method === 'POST') {
                curl_setopt($ch, CURLOPT_POST, true);
                if ($data) {
                    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
                }
            }
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            curl_close($ch);
            
            if ($response === false) {
                if ($attempt < $maxRetries) {
                    sleep($attempt);
                    continue;
                }
                throw new Exception('网络请求失败: ' . $error);
            }
            
            $result = json_decode($response, true);
            
            if ($httpCode === 200) {
                return $result;
            } elseif (in_array($httpCode, [500, 502, 503, 504, 429]) && $attempt < $maxRetries) {
                sleep($attempt);
                continue;
            } else {
                $this->handleErrorResponse($httpCode, $result);
            }
        }
        
        throw new Exception('请求失败,已重试 ' . $maxRetries . ' 次');
    }
    
    /**
     * 处理错误响应
     */
    private function handleErrorResponse($httpCode, $result) {
        $message = isset($result['error']['message']) ? $result['error']['message'] : '未知错误';
        
        switch ($httpCode) {
            case 401:
                throw new Exception('API Key 无效或已过期');
            case 402:
                throw new Exception('调用次数不足,请充值');
            case 400:
                throw new Exception('参数错误: ' . $message);
            case 429:
                throw new Exception('请求频率过高,请稍后重试');
            default:
                throw new Exception('请求失败 (' . $httpCode . '): ' . $message);
        }
    }
    
    /**
     * 发布图文笔记
     */
    public function publishImageNote($title, $content, $images) {
        $data = [
            'api_key' => $this->apiKey,
            'type' => 'normal',
            'title' => $title,
            'content' => $content,
            'images' => $images
        ];
        
        return $this->sendRequest('POST', '/api/rednote/publish', $data);
    }
    
    /**
     * 发布视频笔记
     */
    public function publishVideoNote($title, $content, $video, $cover = null) {
        $data = [
            'api_key' => $this->apiKey,
            'type' => 'video',
            'title' => $title,
            'content' => $content,
            'video' => $video
        ];
        
        if ($cover) {
            $data['cover'] = $cover;
        }
        
        return $this->sendRequest('POST', '/api/rednote/publish', $data);
    }
}

// 使用示例
try {
    $api = new XiaohongshuAPI('your_api_key_here');
    
    // 发布图文笔记
    $imageResult = $api->publishImageNote(
        '美食分享',
        "今天做了超好吃的蛋糕\n#美食 #烘焙",
        [
            'https://picsum.photos/400/400?random=1',
            'https://picsum.photos/400/400?random=2'
        ]
    );

    echo "图文笔记发布成功:\n";
    echo "ID: " . $imageResult['data']['id'] . "\n";
    echo "分享链接: " . $imageResult['data']['url'] . "\n";
    echo "二维码: " . $imageResult['data']['qrcode'] . "\n\n";

    // 发布视频笔记
    $videoResult = $api->publishVideoNote(
        '旅行日记',
        "美丽的海边风景\n#旅行 #海景",
        'https://rednote-publish.oss-cn-hangzhou.aliyuncs.com/public/02-AI-NM.mp4',
        'https://picsum.photos/400/400?random=99'
    );
    
    echo "视频笔记发布成功:\n";
    echo "ID: " . $videoResult['data']['id'] . "\n";
    echo "分享链接: " . $videoResult['data']['url'] . "\n";
    echo "二维码: " . $videoResult['data']['qrcode'] . "\n";
    
} catch (Exception $e) {
    echo '发布失败: ' . $e->getMessage() . "\n";
}
?>
Java
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class XiaohongshuAPI {
    private final String apiKey;
    private final String baseUrl;
    private final OkHttpClient client;
    private final ObjectMapper objectMapper;
    
    public XiaohongshuAPI(String apiKey, String baseUrl) {
        this.apiKey = apiKey;
        this.baseUrl = baseUrl;
        this.objectMapper = new ObjectMapper();
        this.client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
    }
    
    public XiaohongshuAPI(String apiKey) {
        this(apiKey, "https://www.myaibot.vip");
    }
    
    /**
     * 发送POST请求
     */
    private Map<String, Object> sendRequest(String endpoint, Map<String, Object> data) 
            throws IOException, XiaohongshuException {
        
        String url = baseUrl + endpoint;
        String jsonData = objectMapper.writeValueAsString(data);
        
        RequestBody body = RequestBody.create(
                MediaType.parse("application/json"), 
                jsonData
        );
        
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Content-Type", "application/json")
                .post(body)
                .build();
        
        try (Response response = client.newCall(request).execute()) {
            String responseBody = response.body().string();
            Map<String, Object> result = objectMapper.readValue(responseBody, Map.class);
            
            if (response.isSuccessful()) {
                return result;
            } else {
                handleErrorResponse(response.code(), result);
                return null; // 永远不会到达这里
            }
        }
    }
    
    /**
     * 发布图文笔记
     */
    public PublishResult publishImageNote(String title, String content, List<String> images) 
            throws IOException, XiaohongshuException {
        
        Map<String, Object> data = new HashMap<>();
        data.put("api_key", apiKey);
        data.put("type", "normal");
        data.put("title", title);
        data.put("content", content);
        data.put("images", images);
        
        Map<String, Object> response = sendRequest("/api/rednote/publish", data);
        return parsePublishResult(response);
    }
    
    /**
     * 发布视频笔记
     */
    public PublishResult publishVideoNote(String title, String content, String video, String cover) 
            throws IOException, XiaohongshuException {
        
        Map<String, Object> data = new HashMap<>();
        data.put("api_key", apiKey);
        data.put("type", "video");
        data.put("title", title);
        data.put("content", content);
        data.put("video", video);
        if (cover != null) {
            data.put("cover", cover);
        }
        
        Map<String, Object> response = sendRequest("/api/rednote/publish", data);
        return parsePublishResult(response);
    }
    
    // 使用示例
    public static void main(String[] args) {
        XiaohongshuAPI api = new XiaohongshuAPI("your_api_key_here");
        
        try {
            // 发布图文笔记
            List<String> images = Arrays.asList(
                "https://picsum.photos/400/400?random=1",
                "https://picsum.photos/400/400?random=2"
            );
            
            PublishResult imageResult = api.publishImageNote(
                "美食分享",
                "今天做了超好吃的蛋糕\n#美食 #烘焙",
                images
            );
            
            System.out.println("图文笔记发布成功:");
            System.out.println("ID: " + imageResult.getId());
            System.out.println("分享链接: " + imageResult.getUrl());
            System.out.println("二维码: " + imageResult.getQrcode());
            
        } catch (Exception e) {
            System.err.println("发布失败: " + e.getMessage());
        }
    }
}
Bash
# 图文笔记发布示例
curl -X POST https://www.myaibot.vip/api/rednote/publish \
  -H "Content-Type: application/json" \
  -d '{
    "api_key": "YOUR_API_KEY",
    "type": "normal",
    "title": "美食分享",
    "content": "今天做了一道美味的菜\n大家觉得怎么样?",
    "images": [
      "https://picsum.photos/400/400?random=1",
      "https://picsum.photos/400/400?random=2"
    ]
  }'

# 视频笔记发布示例
curl -X POST https://www.myaibot.vip/api/rednote/publish \
  -H "Content-Type: application/json" \
  -d '{
    "api_key": "YOUR_API_KEY",
    "type": "video",
    "title": "旅行日记",
    "content": "美丽的海边风景\n#旅行 #海景",
    "video": "https://rednote-publish.oss-cn-hangzhou.aliyuncs.com/public/02-AI-NM.mp4",
    "cover": "https://picsum.photos/400/400?random=99"
  }'

错误处理最佳实践

统一错误处理

JavaScript
function handleApiError(error) {
  if (error.response) {
    const { status, data } = error.response;

    switch (status) {
      case 401:
        return '请检查 API Key 是否正确或已过期';
      case 402:
        return '调用次数不足,请前往用户中心充值';
      case 400:
        return `参数错误:${data.error?.message || '请检查请求参数'}`;
      case 429:
        return '请求过于频繁,请稍后重试';
      case 500:
        return '服务器临时错误,请稍后重试';
      default:
        return `请求失败:${data.error?.message || '未知错误'}`;
    }
  } else {
    return `网络错误:${error.message}`;
  }
}

重试策略

JavaScript
async function publishWithRetry(data, maxRetries = 3) {
  const retryableErrors = [429, 500, 502, 503, 504];

  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await publishToXiaohongshu(data);
    } catch (error) {
      const shouldRetry = error.response &&
                         retryableErrors.includes(error.response.status);

      if (shouldRetry && attempt < maxRetries) {
        const delay = Math.min(1000 * Math.pow(2, attempt - 1), 10000);
        console.log(`重试第 ${attempt} 次,${delay}ms 后重试...`);
        await new Promise(resolve => setTimeout(resolve, delay));
      } else {
        throw error;
      }
    }
  }
}

立即测试代码

复制上面的代码到你的项目中,替换 API Key 后即可开始使用。 也可以使用我们的在线测试工具快速验证功能。