diff --git a/src/main/java/cn/stock/market/constant/NseIndiaSymbol.java b/src/main/java/cn/stock/market/constant/NseIndiaSymbol.java new file mode 100644 index 0000000..4ae3612 --- /dev/null +++ b/src/main/java/cn/stock/market/constant/NseIndiaSymbol.java @@ -0,0 +1,24 @@ +package cn.stock.market.constant; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +import java.util.Arrays; +import java.util.List; + +@Getter +@AllArgsConstructor +public enum NseIndiaSymbol { + IPL02("IPL02"), + IPHL("IPHL"); + + private String symbol; + + public String getSymbol() { + return symbol; + } + + public static Boolean contains(String symbol) { + return Arrays.stream(NseIndiaSymbol.values()).anyMatch(e -> e.getSymbol().equals(symbol)); + } +} diff --git a/src/main/java/cn/stock/market/utils/NseIndiaRequest.java b/src/main/java/cn/stock/market/utils/NseIndiaRequest.java new file mode 100644 index 0000000..a5d7cf2 --- /dev/null +++ b/src/main/java/cn/stock/market/utils/NseIndiaRequest.java @@ -0,0 +1,75 @@ +package cn.stock.market.utils; + +import okhttp3.*; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class NseIndiaRequest { + private static final String NSE_INDIA_URL = "https://www.nseindia.com"; + private static final OkHttpClient client; + + static { + client = new OkHttpClient.Builder() + .cookieJar(new CookieJar() { + private final Map> cookieStore = new HashMap<>(); + + @Override + public void saveFromResponse(HttpUrl url, List cookies) { + cookieStore.put(url.host(), cookies); + } + + @Override + public List loadForRequest(HttpUrl url) { + List cookies = cookieStore.get(url.host()); + return cookies != null ? cookies : new ArrayList(); + } + }) + .build(); + } + + private static Request createRequest(String url) { + Request request = new Request.Builder() + .url(url) + .header("accept", "application/json, text/plain, */*") + .header("accept-language", "en-US,en;q=0.9") + .header("cache-control", "no-cache") + .header("pragma", "no-cache") + .header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36") + .build(); + + return request; + } + + private static void initCookie() { + Request request = createRequest(NSE_INDIA_URL); + try (Response response = client.newCall(request).execute()) { + if (!response.isSuccessful()) { + throw new IOException("Failed to fetch initial cookies"); + } + } catch (IOException e) { + throw new RuntimeException("Failed to initialize cookies", e); + } + } + + public static String fetchData() { + initCookie(); + + String url = NSE_INDIA_URL + "/api/quote-equity?symbol=IPHL"; + Request request = createRequest(url).newBuilder() + .addHeader("referer", "https://www.nseindia.com/") + .addHeader("origin", "https://www.nseindia.com") + .build(); + try (Response response = client.newCall(request).execute()) { + if (!response.isSuccessful()) { + throw new IOException("Request failed with code: " + response.code()); + } + return response.body().string(); + } catch (IOException e) { + throw new RuntimeException("Failed to fetch data", e); + } + } +} diff --git a/src/main/java/cn/stock/market/web/MoneyApiController.java b/src/main/java/cn/stock/market/web/MoneyApiController.java index e47afb2..36bc746 100644 --- a/src/main/java/cn/stock/market/web/MoneyApiController.java +++ b/src/main/java/cn/stock/market/web/MoneyApiController.java @@ -2,12 +2,13 @@ package cn.stock.market.web; import cn.hutool.core.date.DateUtil; import cn.stock.market.MoneyStockSuggestDTO; +import cn.stock.market.constant.NseIndiaSymbol; import cn.stock.market.domain.basic.entity.MoneyStock; import cn.stock.market.domain.basic.repository.MoneyStockRepository; import cn.stock.market.dto.StockHistoryRequest; import cn.stock.market.dto.StockHistoryResponse; import cn.stock.market.infrastructure.db.po.QMoneyStockPO; -import cn.stock.market.utils.RequestCacheUtils; +import cn.stock.market.utils.NseIndiaRequest; import cn.stock.market.utils.ServerResponse; import cn.stock.market.web.annotations.EncryptFilter; import com.alibaba.fastjson.JSONObject; @@ -40,11 +41,7 @@ import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.util.*; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.logging.Logger; import java.util.stream.Collectors; /** @@ -65,27 +62,6 @@ public class MoneyApiController { private static final String EXTERNAL_API_URL = "https://priceapi.moneycontrol.com/techCharts/indianMarket/stock/history"; - private static final OkHttpClient client; - - static { - client = new OkHttpClient.Builder() - .cookieJar(new CookieJar() { - private final Map> cookieStore = new HashMap<>(); - - @Override - public void saveFromResponse(HttpUrl url, List cookies) { - cookieStore.put(url.host(), cookies); - } - - @Override - public List loadForRequest(HttpUrl url) { - List cookies = cookieStore.get(url.host()); - return cookies != null ? cookies : new ArrayList(); - } - }) - .build(); - } - @ApiOperation(value = "股票详情信息",httpMethod = "GET") @ApiImplicitParams({ @ApiImplicitParam(name="stockType",value = "BSE或者NSE"), @@ -194,12 +170,6 @@ public class MoneyApiController { @EncryptFilter(decryptRequest = false) public ServerResponse getStockDetail(@RequestParam String stockType, @RequestParam String symbol ) { - String url = ""; - if(symbol.equals("IPL02") || symbol.equals("IPHL")){ - url = "https://www.nseindia.com/api/quote-equity?symbol=IPHL"; - }else { - url = String.format("https://priceapi.moneycontrol.com/pricefeed/%s/equitycash/%s",stockType,symbol); - } MoneyStock moneyStock = moneyStockRepository.findOne(QMoneyStockPO.moneyStockPO.stockType.eq(stockType) .and(QMoneyStockPO.moneyStockPO.moneyScId.eq(symbol)) .and(QMoneyStockPO.moneyStockPO.isLock.eq(0)) @@ -209,76 +179,41 @@ public class MoneyApiController { return ServerResponse.createByErrorMsg("没有找到该股票"); }*/ // 设置重试次数 - if(symbol.equals("IPL02") || symbol.equals("IPHL")){ + if(NseIndiaSymbol.contains(symbol)){ try { - String initialUrl = "https://www.nseindia.com/"; - Request initialRequest = new Request.Builder() - .url(initialUrl) - .header("accept", "application/json, text/plain, */*") - .header("accept-language", "en-US,en;q=0.9") - .header("cache-control", "no-cache") - .header("pragma", "no-cache") - .header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36") - .build(); + // Process the response + String responseBody = NseIndiaRequest.fetchData(); + JSONObject jsonData = JSONObject.parseObject(responseBody); + JSONObject json1 = new JSONObject(); - try (Response initialResponse = client.newCall(initialRequest).execute()) { - if (!initialResponse.isSuccessful()) { - throw new IOException("Failed to fetch initial cookies"); + JSONObject data =jsonData.getJSONObject("priceInfo"); + if(data!=null){ + json1.put("company","Indian Phosphate Limited"); + json1.put("pricepercentchange",data.getString("pChange")); + json1.put("stockType",stockType); + json1.put("pricechange",data.getString("change")); + json1.put("pricecurrent",data.getString("lastPrice")); + json1.put("priceprevclose",data.getString("previousClose")); + json1.put("PREVDATE",""); + json1.put("VOL",jsonData.getJSONObject("preOpenMarket").getString("totalTradedVolume")); + json1.put("dataSourceType","3"); + json1.put("symbol",symbol); + json1.put("BSEID",symbol); + json1.put("NSEID",symbol); + json1.put("LTH",data.getString("upperCP")); + json1.put("LTL",data.getString("lowerCP")); + json1.put("OPN",data.getString("open")); + if(null!=moneyStock){ + json1.put("id",moneyStock.getId()); } } - Request request = new Request.Builder() - .url(url) - .header("accept", "application/json, text/plain, */*") - .header("accept-language", "en-US,en;q=0.9") - .header("cache-control", "no-cache") - .header("pragma", "no-cache") - .header("user-agent", "Mozilla/5.0") - .header("referer", "https://www.nseindia.com/") - .header("origin", "https://www.nseindia.com") - .header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36") - .build(); + return ServerResponse.createBySuccess(json1); - try (Response response = client.newCall(request).execute()) { - if (!response.isSuccessful()) { - throw new IOException("Request failed with code: " + response.code()); - } - - // Process the response - String responseBody = response.body().string(); - JSONObject jsonData = JSONObject.parseObject(responseBody); - JSONObject json1 = new JSONObject(); - - JSONObject data =jsonData.getJSONObject("priceInfo"); - if(data!=null){ - json1.put("company","Indian Phosphate Limited"); - json1.put("pricepercentchange",data.getString("pChange")); - json1.put("stockType",stockType); - json1.put("pricechange",data.getString("change")); - json1.put("pricecurrent",data.getString("lastPrice")); - json1.put("priceprevclose",data.getString("previousClose")); - json1.put("PREVDATE",""); - json1.put("VOL",jsonData.getJSONObject("preOpenMarket").getString("totalTradedVolume")); - json1.put("dataSourceType","3"); - json1.put("symbol",symbol); - json1.put("BSEID",symbol); - json1.put("NSEID",symbol); - json1.put("LTH",data.getString("upperCP")); - json1.put("LTL",data.getString("lowerCP")); - json1.put("OPN",data.getString("open")); - if(null!=moneyStock){ - json1.put("id",moneyStock.getId()); - } - } - return ServerResponse.createBySuccess(json1); - - } catch (IOException e) { - throw new RuntimeException("Failed to fetch data", e); - } - - } catch (IOException e) { - throw new RuntimeException("Failed to initialize cookies", e); + } catch (Exception e) { + throw new RuntimeException("Failed to fetch data", e); } }else { + String url = String.format("https://priceapi.moneycontrol.com/pricefeed/%s/equitycash/%s",stockType,symbol); int maxRetries = 3; for (int retry = 1; retry <= maxRetries; retry++) { try {