工具方法
This commit is contained in:
@@ -2,6 +2,7 @@ package cn.stock.market.utils;
|
|||||||
|
|
||||||
|
|
||||||
import java.io.BufferedReader;
|
import java.io.BufferedReader;
|
||||||
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.io.InputStreamReader;
|
import java.io.InputStreamReader;
|
||||||
import java.net.HttpURLConnection;
|
import java.net.HttpURLConnection;
|
||||||
@@ -142,6 +143,52 @@ public class HttpRequest {
|
|||||||
return text;
|
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) {
|
public static void main(String[] args) {
|
||||||
String url = "";
|
String url = "";
|
||||||
|
|||||||
Reference in New Issue
Block a user