解决 .net HttpClient 调用时出现的 "A task was cancelled" 错误

近日在系统中集成ElasticClient客户端,自动创建索引、删除索引,发现通过 ElasticClient 的 LowerLevelClient 无法正确返回结果,但是索引已成功创建或删除。

并会在超时时间呢抛出异常”A task was cancelled“,查阅官方文档和Google都无解。

早上重新尝试,改用HttpClient直接进行访问,依然是一样的问题。

无奈,祭出Fiddler,进行请求分析。

1)使用Composer模拟请求,最简单的GET操作,居然也不能立即返回结果

 

2)使用浏览器直接访问,能够正确返回结果

 

3)比较Http 请求头,Fiddler 请求头基本都是空的,从浏览器复制Fiddler的请求头过来,最终发现,加上下面的请求头,就能正确返回结果:

Accept-Encoding: gzip, deflate

 

4)对应HttpClient来说,就可以用下面的方法解决了

HttpClientHandler handler = new HttpClientHandler()
            {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            };

            var httpClient = new HttpClient(handler)
            {
                BaseAddress = new Uri($"http://{es_host}:{es_port}")
            };

使用这个HttpClient再去访问ElasticSearch,立即就能返回结果。

 

问题分析:服务器端默认情况下返回结果就会使用Gzip压缩,但是客户端默认不处理数据解压,就导致客户端读取数据时,无法判断数据是否已经读取完毕,就一直挂起,直到超时,然后抛出”A task was canceled" 错误。

 HttpClient 其他的 “A task was Canceled” 错误,很可能也是因为Http头设置不正确造成的,而服务器对客户端特性有要求,如本例的Gzip。 

 

 

转载于:https://www.cnblogs.com/mobwiz/p/7908434.html

import requests import time import json import webbrowser API_URL = "https://ai.gitee.com/v1/async/audio/speech" API_TOKEN = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" headers = { "Authorization": f"Bearer {API_TOKEN}" } def query(payload): response = requests.post(API_URL, headers=headers, json=payload) return response.json() def poll_task(task_id): status_url = f"https://ai.gitee.com/v1/task/{task_id}" timeout = 30 * 60 retry_interval = 10 attempts = 0 max_attempts = int(timeout / retry_interval) while attempts < max_attempts: attempts += 1 print(f"Checking task status [{attempts}]...", end="") response = requests.get(status_url, headers=headers, timeout=10) result = response.json() if result.get("error"): print('error') raise ValueError(f"{result['error']}: {result.get('message', 'Unknown error')}") status = result.get("status", "unknown") print(status) if status == "success": if "output" in result and "file_url" in result["output"]: file_url = result["output"]["file_url"] duration = (result.get('completed_at', 0) - result.get('started_at', 0)) / 1000 print(f"🔗 Donwload link: {file_url}") print(f"⏱️ Task duration: {duration:.2f} seconds") # Open the result URL in the browser webbrowser.open(file_url) else: print("⚠️ No output URL found") elif status in ["failed", "cancelled"]: print(f"❌ Task {status}") else: time.sleep(retry_interval) continue task_file = f"task_{task_id}.json" with open(task_file, "w") as f: json.dump(result, f, indent=4) print(f"Task was saved to file {task_file}") return result print(f"⏰ Maximum attempts reached ({max_attempts})") return {"status": "timeout", "message": "maximum wait time exceeded"} if __name__ == "__main__": print("Creating task...") result = query({ "inputs": "Hello, world!", "model": "Spark-TTS-0.5B", "gender": "male", "pitch": 3, "speed": 3 }) task_id = result.get("task_id") if not task_id: raise ValueError("Task ID not found in the response") print(f"Task ID: {task_id}") task = poll_task(task_id) if task.get("status") == "success": # Do something with the task result here print("Task completed successfully!") 将这段程序替换成java代码
最新发布
06-22
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值