From 67a3d6fd74c8b7341e526708cfac6f2906499cc6 Mon Sep 17 00:00:00 2001 From: zhanghuilong Date: Fri, 31 May 2024 17:49:52 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B7=A5=E5=85=B7=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cn/stock/market/utils/HttpRequest.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/src/main/java/cn/stock/market/utils/HttpRequest.java b/src/main/java/cn/stock/market/utils/HttpRequest.java index a2f1770..dce1961 100644 --- a/src/main/java/cn/stock/market/utils/HttpRequest.java +++ b/src/main/java/cn/stock/market/utils/HttpRequest.java @@ -2,6 +2,7 @@ package cn.stock.market.utils; import java.io.BufferedReader; +import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; @@ -142,6 +143,52 @@ public class HttpRequest { return text; } + public static String doTwelveGet(String url) throws Exception{ + int maxRetries = 3; + for (int retry = 1; retry <= maxRetries; retry++) { + BufferedReader reader = null; + StringBuilder response = new StringBuilder(); + try { + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + con.setRequestMethod("GET"); + con.setRequestProperty("Accept", "application/json"); + con.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); + //模拟postman请求,否则返回403 + con.setRequestProperty("User-Agent", "PostmanRuntime/7.26.8"); + + int responseCode = con.getResponseCode(); + if (responseCode == HttpURLConnection.HTTP_OK) { + reader = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = reader.readLine()) != null) { + response.append(inputLine); + } + reader.close(); + return response.toString(); + } else { + log.error("HTTP request failed with response code: " + responseCode); + } + }catch(Exception e) { + log.error("请求twelvedata数据url:{},exception:{} ", url,e); + }finally { + if (reader != null) { + reader.close(); + } + } + // 如果不是最后一次重试,则等待一段时间再进行下一次重试 + if (retry < maxRetries) { + try { + // 1秒钟 + Thread.sleep(1000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + } + return null; + } + public static void main(String[] args) { String url = "";