You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Twitter API修改头像时遇'Expecting value: line1 column1'错误求助

问题分析与解决方案

你遇到的'Expecting value: line 1 column 1 (char 0)'错误,本质是API返回的内容不是有效JSON(大概率是错误页面或空响应),根源是你的请求格式完全不符合Twitter API的要求,具体问题和修正如下:

核心问题点

  • 请求参数传递错误:update_profile_image接口要求通过multipart/form-data表单上传图片二进制数据,你却把base64编码的图片放到URL参数(params)里,完全不符合接口规范。
  • Content-Type头设置错误:手动指定'Content-Type': 'multipart/form-data'会导致requests无法自动生成正确的请求边界(boundary),服务器无法解析你的请求。
  • 认证方式不规范:虽然你用了auth_token cookie,但Twitter官方API推荐使用OAuth 1.0a进行用户上下文认证,cookie认证可能不稳定或被拦截。

修正后的代码

import os
import random
from os.path import isfile, join
import requests

# 随机选择图片
picture = [f for f in os.listdir("pfp/") if isfile(join("pfp/", f))]
random_picture = random.choice(picture)

# 准备请求参数
cookies = {
    'auth_token': '你的auth_token值'
}
# 不要手动设置Content-Type,让requests自动处理
headers = {}

# 用files参数上传图片二进制数据
with open(f'pfp/{random_picture}', "rb") as image_file:
    files = {'image': image_file}
    response = requests.post(
        'https://api.twitter.com/1.1/account/update_profile_image.json',
        cookies=cookies,
        files=files,
        proxies=proxies
    )

# 先打印响应内容排查问题
print(response.text)
# 再尝试解析JSON
try:
    print(response.json())
except Exception as e:
    print(f"解析JSON失败: {e}")

额外建议

  • 优先使用官方认证方式:Twitter API v1.1的用户操作接口(比如修改头像)需要OAuth 1.0a认证,使用requests-oauthlib库处理会更稳定,避免cookie失效问题。
  • 排查响应内容:遇到JSON解析错误时,先打印response.text和response.status_code,能快速定位是认证失败、请求格式错误还是其他服务器问题。

内容的提问来源于stack exchange,提问作者nicvaldy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 19:40:57