| | |
| | | package org.example.common; |
| | | |
| | | import com.fasterxml.jackson.core.type.TypeReference; |
| | | import com.google.gson.Gson; |
| | | import okhttp3.OkHttpClient; |
| | | import okhttp3.Request; |
| | | import okhttp3.Response; |
| | | import okhttp3.logging.HttpLoggingInterceptor; |
| | | import java.io.BufferedReader; |
| | | import java.io.InputStreamReader; |
| | | import java.net.HttpURLConnection; |
| | | import java.net.URL; |
| | | |
| | | import java.io.IOException; |
| | | import java.util.Map; |
| | | import java.util.concurrent.TimeUnit; |
| | | |
| | | /** |
| | | * @program: demo |
| | | * @description: |
| | | * @create: 2024-07-17 16:04 |
| | | **/ |
| | | public class MarketDataClient { |
| | | |
| | | private static final String REQUEST_HOST = "https://api.mexc.com"; |
| | | private static final OkHttpClient OK_HTTP_CLIENT = createOkHttpClient(); |
| | | |
| | | private static OkHttpClient createOkHttpClient() { |
| | | HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); |
| | | httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); |
| | | return new OkHttpClient.Builder() |
| | | .connectTimeout(45, TimeUnit.SECONDS) |
| | | .readTimeout(45, TimeUnit.SECONDS) |
| | | .writeTimeout(45, TimeUnit.SECONDS) |
| | | //.addInterceptor(httpLoggingInterceptor) |
| | | .build(); |
| | | } |
| | | |
| | | |
| | | public static <T> T get(String uri, Map<String, String> params, TypeReference<T> ref) { |
| | | public static String doGet(String apiUrl) { |
| | | try { |
| | | Request.Builder builder = new Request.Builder().url(REQUEST_HOST + uri + "?" + SignatureUtil.toQueryString(params)).get(); |
| | | Response response = OK_HTTP_CLIENT.newCall(builder.build()).execute(); |
| | | Gson gson = new Gson(); |
| | | assert response.body() != null; |
| | | String content = response.body().string(); |
| | | return gson.fromJson(content, ref.getType()); |
| | | } catch (IOException e) { |
| | | throw new RuntimeException(e); |
| | | URL url = new URL(apiUrl); |
| | | HttpURLConnection connection = (HttpURLConnection) url.openConnection(); |
| | | connection.setRequestMethod("GET"); |
| | | |
| | | BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); |
| | | String inputLine; |
| | | StringBuilder response = new StringBuilder(); |
| | | |
| | | while ((inputLine = in.readLine()) != null) { |
| | | response.append(inputLine); |
| | | } |
| | | in.close(); |
| | | return response.toString(); |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | |
| | | } |