ใช้ Java Gson อ่าน API coingecko เพื่อ feed ราคาเหรียญ
ขอเอาตัวอย่าง Code แปะเลยละกันนะครับ อันนี้เอาไว้ดูกันลืมเฉยๆ อ่ะนะ แต่ถ้าเพื่อนๆ ดูก็น่าจะพอได้ไอเดียนะครับลองดูครับผม
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class CgcV2 {
public void executeCurl(String tokenID, String startDateStr,
String endDateStr) {
StringBuffer stringA = new StringBuffer();
try {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date startDate = formatter.parse(startDateStr);
Date endDate = formatter.parse(endDateStr);
String unixStart = String.valueOf(startDate.getTime()).substring(0,10);
String unixEnd = String.valueOf(endDate.getTime()).substring(0,10);
String uri = "https://api.coingecko.com/api/v3/coins/" + tokenID
+ "/market_chart/range?vs_currency=usd&from=" + unixStart
+ "&to=" + unixEnd + "";
System.out.println(uri);
ProcessBuilder processBuilder = new ProcessBuilder();
String command = "curl --location --request GET " + uri;
processBuilder.command(command.split(" "));
stringA = new StringBuffer();
try {
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
stringA.append(line + "\n");
}
System.out.println(stringA.toString());
JsonParser parser = new JsonParser();
JsonObject root = parser.parse(stringA.toString()).getAsJsonObject();
JsonArray priceList = root.get("prices").getAsJsonArray();
for(JsonElement priceObj:priceList){
String data=priceObj.toString();
String uDate=data.split(",")[0];
String price=data.split(",")[1];
uDate=data.split(",")[0].substring(1,uDate.length());
price=data.split(",")[1].substring(0,price.length()-1);
Date date = new Date ();
date.setTime((long)Long.parseLong(uDate));
String dDate=formatter.format(date);
System.out.println("Date "+dDate+" Price "+price);
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CgcV2 c = new CgcV2();
c.executeCurl("0x", "01-01-2021", "08-08-2021");
Date date = new Date ();
date.setTime((long)Long.parseLong("1628294400000")*1000);
System.out.println(date);
}
}
ความคิดเห็น
แสดงความคิดเห็น