post请求上传二进制文件问题:request.post()

开发板:QuecDuino EVB V1.1,模组:EC800M-CNGB

功能:通过request.post()向阿里智能语音平台发送录音文件,进行语音识别。

错误:OSError: -104

不知道问题所在。

-- coding: UTF-8 --

import request import ujson,uio

def process(my_request, token, audioFile) :

# 读取音频文件

with uio.open(audioFile, mode = 'rb') as f:
    audioContent = f.read()
    
print(len(audioContent))

# 设置HTTPS请求头部
httpHeaders = {
    'X-NLS-Token': token,
    'Content-Type': 'application/octet-stream',
    'Content-Length': str(len(audioContent))
    }

response=request.post(url=my_request,data=audioContent,headers=httpHeaders)


print('Response status and response reason:')
print(response.status ,response.reason)

body = response.read()
try:
    print('Recognize response is:')
    body = ujson.loads(body)
    print(body)

    status = body['status']
    if status == 20000000 :
        result = body['result']
        print('Recognize result: ' + result)
    else :
        print('Recognizer failed!')

except ValueError:
    print('The response is not json format string')

conn.close()

appKey = ‘M6QJ2YbpCx8SoCGR’ token = ‘1ad5e7992597420db954c703c922c881’

服务请求地址

url = ‘https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/asr

音频文件

audioFile = ‘/usr/nls-sample-16k.wav’ format = ‘pcm’ sampleRate = 16000 enablePunctuationPrediction = True enableInverseTextNormalization = True enableVoiceDetection = False

设置RESTful请求参数

my_request = url + ‘?appkey=’ + appKey my_request = my_request + ‘&format=’ + format my_request = my_request + ‘&sample_rate=’ + str(sampleRate)

if enablePunctuationPrediction : my_request = my_request + ‘&enable_punctuation_prediction=’ + ‘true’

if enableInverseTextNormalization : my_request = my_request+ ‘&enable_inverse_text_normalization=’ + ‘true’

if enableVoiceDetection : my_request = my_request + ‘&enable_voice_detection=’ + ‘true’

print('my_request: ’ + my_request)

process(my_request, token, audioFile)

报错为连接被对方主动断开了. 请确认服务器是否可以正常Get/Post数据后在做测试.

Bullee Yu:

非常感谢回复,使我知道了QuecPython 错误码的查询文档的位置。

我的问题已经解决。根本原因是QuecPython的HTTP请求中,自动携带了如下头信息:

httpHeaders = {
    'Content-Length': str(len(your_file_path))
    }

如果你再人工添加这个数据长度头信息,Nginx服务器就会报如下错误并返回400:

2025/10/31 14:20:06 [info] 1850153#0: *166516 client sent duplicate header line: “Content-Length: 480960”, previous value: “Content-Length: 480960” while reading client request headers, client: 223.104.68.9, server: fangdeco.cn, request: “POST /api/upload-audio/ HTTP/1.0”, host: “www.fangdeco.cn”2025/10/31 14:20:10 [info] 1850153#0: *166516 recv() failed (104: Connection reset by peer) while reading client request headers, client: 223.104.68.9, server: fangdeco.cn, request: “POST /api/upload-audio/ HTTP/1.0”, host: “www.fangdeco.cn

client sent duplicate header line意思就是说客户端发送的重复的头文件信息,即:Content-Length: 480960

跟大家分享一个收获:Nginx 服务器的日志文件默认不会记录这种低级的显而易见的错误,只会返回一个简单的400网页信息。要阅读详细信息,你需要在nginx.conf配置文件中添加详细信息log及access详细输出指令,具体查豆包或deepseek。