503, https://www.dmxapi.cn/v1/chat/completions at com.sopwr.scrape.common.HtmlUt...
错误信息
com.sopwr.scrape.common.model.WorkerException: java.lang.RuntimeException: ERROR 503, https://www.dmxapi.cn/v1/chat/completions
at com.sopwr.scrape.common.HtmlUtil.request(HtmlUtil.java:396)
at com.sopwr.scrape.common.HtmlUtil.requestJson(HtmlUtil.java:635)
at com.sopwr.scrape.common.HtmlUtil.requestJson(HtmlUtil.java:614)
at com.sopwr.server.cache.TestDmxapi.main(TestDmxapi.java:22)
Caused by: java.lang.RuntimeException: ERROR 503, https://www.dmxapi.cn/v1/chat/completions
at com.sopwr.scrape.common.HtmlUtil.request(HtmlUtil.java:372)
AI 解决方案
🔍 错误分析
1. 🌐 错误翻译
原文:com.sopwr.scrape.common.model.WorkerException: java.lang.RuntimeException: ERROR 503, https://www.dmxapi.cn/v1/chat/completions
译文:com.sopwr.scrape.common.model.WorkerException:java.lang.RuntimeException:错误 503,https://www.dmxapi.cn/v1/chat/completions
2. 🎯 原因分析
HtmlUtil.request() 方法的第372行和396行发起的HTTP请求失败TestDmxapi.main() 方法调用 HtmlUtil.requestJson() 时触发了底层HTTP请求,最终抛出503错误3. 💡 解决方案
由于503错误是服务端问题,客户端需要添加重试机制和超时处理:
// 在请求方法中添加重试逻辑和超时配置
public static String requestJson(String url, String jsonPayload, int maxRetries) throws WorkerException {
int attempt = 0;
while (attempt <= maxRetries) {
try {
// 构建带超时设置的HTTP请求
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(url))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(10)) // 10秒超时
.POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
return response.body();
} else if (response.statusCode() == 503 && attempt < maxRetries) {
attempt++;
Thread.sleep(1000 * attempt); // 指数退避重试
continue;
} else {
throw new WorkerException("HTTP Error: " + response.statusCode());
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new WorkerException("Request interrupted", e);
} catch (Exception e) {
if (attempt >= maxRetries) {
throw new WorkerException("Max retries exceeded", e);
}
attempt++;
try {
Thread.sleep(1000 * attempt);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new WorkerException("Request interrupted", ie);
}
}
}
throw new WorkerException("Request failed after " + maxRetries + " retries");
}
使用时调用:
// 修改TestDmxapi.main方法中的调用
public static void main(String[] args) {
try {
String result = HtmlUtil.requestJson("https://www.dmxapi.cn/v1/chat/completions", payload, 3);
System.out.println(result);
} catch (WorkerException e) {
e.printStackTrace();
// 记录重试失败日志,考虑降级处理
}
}
4. 🛡️ 预防措施
推荐工具: