Python Requests调用LinkedIn接口正常,Curl请求失败原因排查
Python Requests成功但Curl请求LinkedIn失败的原因分析
问题背景
使用保存的LinkedIn会话发送消息时,Python Requests请求可正常执行,但参数看似一致的Curl请求却无法工作,以下是两者的核心差异及失败原因:
核心差异与失败原因
1. Content-Length头部与实际请求体长度不匹配
Python代码中Content-Length: 489是json.dumps生成的无缩进JSON字符串的准确长度,但Curl的--data-raw中包含换行和缩进,实际请求体长度远大于489。手动指定错误的Content-Length会触发LinkedIn服务器的校验逻辑,直接拒绝请求。
2. X-LI-Track头部的Shell解析问题
Python里的X-LI-Track值用转义双引号\"保证JSON格式正确,但Curl命令中直接使用未转义的双引号,在bash等shell环境下会被错误解析:shell会将双引号内的内容分割为多个参数,导致头部内容缺失或格式损坏,LinkedIn无法识别这个关键的客户端标识头部。
3. 缺失会话Cookie
Python Requests基于保存的会话发起请求时,会话已包含LinkedIn的身份验证Cookie(如li_at、JSESSIONID等),但Curl命令未通过--cookie参数传递这些Cookie,导致请求未通过身份验证,被服务器拒绝。
修正后的Curl命令示例
curl -X POST \ 'https://www.linkedin.com/voyager/api/messaging/conversations?action=create' \ --header 'Host: www.linkedin.com' \ --header 'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/110.0' \ --header 'Accept: application/json' \ --header 'Accept-Language: en-US,en;q=0.5' \ --header 'Accept-Encoding: gzip, deflate, br' \ --header 'Referer: https://www.linkedin.com/search/results/people/?keywords=ali&origin=SWITCH_SEARCH_VERTICAL&sid=HnO' \ --header 'x-restli-protocol-version: 2.0.0' \ --header 'X-LI-Lang: en_US' \ --header 'X-LI-Track: {\"clientVersion\":\"1.12.9\",\"mpVersion\":\"1.12.9\",\"osName\":\"web\",\"timezoneOffset\":5,\"timezone\":\"Asia/Karachi\",\"deviceFormFactor\":\"DESKTOP\",\"mpName\":\"voyager-web\",\"displayDensity\":1,\"displayWidth\":1920,\"displayHeight\":1080}' \ --header 'X-li-page-instance: urn:li:page:d_flagship3_search_srp_people;zn3gn3MTTl6ilgF+0KG8hA==' \ --header 'Csrf-Token: ajax:your session' \ --header 'Content-Type: text/plain;charset=UTF-8' \ --header 'Origin: https://www.linkedin.com' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-origin' \ --header 'TE: trailers' \ --cookie "li_at=your_session_cookie; JSESSIONID=your_jsessionid" \ --data-raw '{"keyVersion":"LEGACY_INBOX","conversationCreate":{"eventCreate":{"value":{"com.linkedin.voyager.messaging.create.MessageCreate":{"attributedBody":{"text":"message","attributes":[]},"attachments":[]}}},"recipients":["ACoAACAAZBIBVTrxu7umYeGDknEvSHy6CbWpFGI"],"subtype":"MEMBER_TO_MEMBER"}'
修正点说明:
- 移除手动指定的
Content-Length,让Curl自动计算实际请求体长度 - 转义
X-LI-Track中的双引号,避免Shell解析错误 - 添加
--cookie参数,传入LinkedIn会话的身份验证Cookie - 将
--data-raw中的JSON压缩为单行,确保格式与Python请求一致
内容的提问来源于stack exchange,提问作者foragerDev
相关产品推荐
相关产品推荐

