使用Python调用LinkedIn API上传图片时遇400错误:请求体不可为空
LinkedIn API图片上传报错:Empty entity body is not allowed for create method request
问题详情
完成图片上传初始化步骤后,执行图片上传时收到400错误响应:
{
"message": "Empty entity body is not allowed for create method request",
"status": 400
}
相关代码
image_post方法
def image_post(self, image_title, image_url, return_urn=False): url = f"{LINKEDIN_URL}images?action=initializeUpload" payload = { "initializeUploadRequest": { "owner": self.__linkedin_urn } } response_init = requests.post(url=url, headers=self.__headers, json=payload) LOGGER.info(response_init.json()) LOGGER.info(response_init.status_code) try: response_json = response_init.json() upload_url = response_json['value']['uploadUrl'] image = response_json['value']['image'] mimetype, _ = mimetypes.guess_type(image_url) headers = { 'Authorization': 'Bearer Redacted', 'Content-Type': mimetype if mimetype else 'application/octet-stream' } response = requests.post(url=upload_url, headers=headers, files={"file": (image_url, self.__media_to_bytes(image_url))}) LOGGER.info(response.json()) LOGGER.info(response.status_code) if response.status_code != 201: LOGGER.error("Image Upload Failed") return Response(content=json.dumps({"message": "Failed to upload image"}), status_code=status.HTTP_400_BAD_REQUEST) if not return_urn: self.__payload = { "author": self.__linkedin_urn, "commentary": self.request.get('commentary'), "visibility": "PUBLIC", "distribution": { "feedDistribution": "MAIN_FEED", "targetEntities": [], "thirdPartyDistributionChannels": [] }, "content": { "media": { "title": image_title, "id": image } }, "lifecycleState": "PUBLISHED", "isReshareDisabledByAuthor": False } else: return image except Exception as e: LOGGER.error(e) return Response(content=json.dumps(response_init.json()), status_code=response_init.status_code)
请求头定义
self.__headers = { 'Authorization': f'Bearer {self.__access_token}', 'Content-Type': 'application/json', 'Linkedin-Version': '202304' }
帖子发布方法
def __create_post(self, post_type): url = f"{LINKEDIN_URL}posts" post = Posts(self.request, self.__linkedin_urn, self.__get_headers(), post_type=post_type) self.__response = requests.post(url=url, headers=self.__get_headers(), json=post.get_payload())
修复方案
核心问题分析
报错的直接原因:
- 使用了错误的请求方法(POST),LinkedIn图片上传接口要求用PUT提交二进制数据
files参数生成了multipart/form-data格式请求,不符合接口对原始二进制流的要求- 硬编码Authorization头的token,可能导致认证无效
- 未校验图片二进制数据是否为空
修改后的上传代码片段
# 替换原上传请求部分的代码 mimetype, _ = mimetypes.guess_type(image_url) headers = { 'Authorization': f'Bearer {self.__access_token}', # 使用实际有效token 'Content-Type': mimetype if mimetype else 'application/octet-stream' } # 校验图片数据有效性 image_data = self.__media_to_bytes(image_url) if not image_data: LOGGER.error("Image data is empty or invalid") return Response(content=json.dumps({"message": "Invalid image content"}), status_code=status.HTTP_400_BAD_REQUEST) # 使用PUT请求直接发送二进制数据 response = requests.put(url=upload_url, headers=headers, data=image_data)
关键修改说明
- 请求方法变更:将
requests.post改为requests.put,匹配LinkedIn接口要求 - 请求格式调整:去掉
files参数,改用data传递二进制数据,确保请求体为原始图片字节流 - token正确性:使用初始化时的
self.__access_token,避免硬编码导致的认证问题 - 数据校验:增加图片数据非空校验,提前拦截无效输入
内容的提问来源于stack exchange,提问作者Neha
相关产品推荐
相关产品推荐

