您好,我正在尝试使用 linkedin api 发布图像和内容,但我的代码中出现以下错误。 这是我在 python django 中的代码:-
def post_content(access_token, user_id, content, image_path):
try:
POST_URL = 'https://api.linkedin.com/v2/ugcPosts'
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
"LinkedIn-Version": "202402",
"X-Restli-Protocol-Version": "2.0.0"
}
# Initialize image upload
initialize_upload_request = {
"initializeUploadRequest": {
"owner": f"urn:li:person:{user_id}"
}
}
print("upload Payload:")
print(json.dumps(initialize_upload_request, indent=4))
initialize_upload_response = requests.post(
"https://api.linkedin.com/rest/images?action=initializeUpload",
json=initialize_upload_request,
headers=headers # Pass the headers here
)
initialize_upload_data = initialize_upload_response.json()
upload_url = initialize_upload_data['value']['uploadUrl']
image_urn = initialize_upload_data['value']['image']
# Upload image
with open(image_path, 'rb') as file:
response = requests.put(upload_url, data=file)
response.raise_for_status() # Raise exception if upload fails
# Post content
request_data = {
"author": f"urn:li:person:{user_id}",
"lifecycleState": "PUBLISHED",
"specificContent": {
"com.linkedin.ugc.ShareContent": {
"shareCommentary": {
"text": content
},
"shareMediaCategory": "IMAGE",
"media": [
{
"status": "READY",
"media": image_urn
}
]
}
},
"visibility": {
"com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
}
}
print("Request Payload:")
print(json.dumps(request_data, indent=4))
post_response = requests.post(POST_URL, json=request_data, headers=headers)
print("ecec",post_response.json())
if post_response.ok:
print("Content posted successfully.")
return {'success': True}
else:
error_message = post_response.text
print(f"Failed to post content: {error_message}")
return {'success': False, 'error': error_message}
except Exception as e:
print(f"Error posting content: {str(e)}")
return {'success': False, 'error': str(e)}
这是我尝试发布内容时出现的错误:-
Failed to post content: {"errorDetailType":"com.linkedin.common.error.BadRequest","message":"com.linkedin.content.common.exception.BadRequestResponseException: One or more of the contents is not owned by the author. All contents must be owned by the author","errorDetails":{"inputErrors":[{"description":"Content(s) you provided must be owned by post author","input":{},"code":"INVALID_CONTENT_OWNERSHIP"}]},"status":400}
我在文档中的任何位置都找不到此错误代码,并且在看到上传和请求负载后,所有者和作者是相同的。我看到另一篇文章,其中有人遇到此错误,但没有解决方案。
我发现错误是因为我使用的是ugc post,而旧的json请求数据使用最新的允许我发布。